Linux 我需要在Shell脚本中获得一个子字符串

Linux 我需要在Shell脚本中获得一个子字符串,linux,string,shell,sed,Linux,String,Shell,Sed,我需要帮助 我需要在下一行中得到一个子字符串 11:46:24.851239 IP (tos 0x0, ttl 128, id 11289, offset 0, flags [none], proto UDP (17), length 229) 结果必须是:ttl 128 我希望你能帮助我 谢谢 尝试这样做: echo '11:46:24.851239 IP (tos 0x0, ttl 128, id 11289, offset 0, flags [none], proto UDP (17),

我需要帮助

我需要在下一行中得到一个子字符串

11:46:24.851239 IP (tos 0x0, ttl 128, id 11289, offset 0, flags [none], proto UDP (17), length 229)
结果必须是:
ttl 128

我希望你能帮助我

谢谢

尝试这样做:

echo '11:46:24.851239 IP (tos 0x0, ttl 128, id 11289, offset 0, flags [none], proto UDP (17), length 229)' |
grep -oP "\bttl\s+\d+\b"
ttl 128
  • \b
    是单词边界
  • \s
    是一个空格
  • +
    表示至少一个或多个前置字符
  • -P
    开关是用于
    grep
  • -o
    开关意味着只打印匹配的部分
编辑 如果要将其放入变量中:

var=$(
    echo '11:46:24.851239 IP (tos 0x0, ttl 128, id 11289, offset 0, flags [none], proto UDP (17), length 229)' |
        grep -oP "\bttl\s+\d+\b"
)
echo "$var"

尝试使用
grep-o'ttl[0-9]\+'

$ echo '11:46:24.851239 IP (tos 0x0, ttl 128, id 11289, offset 0, flags [none], proto UDP (17), length 229)' | grep -o 'ttl [0-9]\+'
ttl 128
使用:


@然后再投你的一票作为安慰。当然,这个答案也是+1。我可以这样做吗:var=ttl echo'11:46:24.851239 IP(tos 0x0,ttl 128,id 11289,偏移量0,标志[none],proto UDP(17),长度229)“grep-oP”\b$var\s+\d+\b”
sed 's/.*[ ]*\(ttl[ ]*[0-9]*\).*/\1/' input