Skip to content
Advertisement

I need get a substring in Shell Script

i need help.

I need get a substring in the next line

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

the result must be: ttl 128

I hope you can help me!

Thanks!

Advertisement

Answer

Try doing this :

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

NOTE

  • b is a word boundary
  • s is a space
  • + mean at least one or more preceding character
  • -P switch is pcre advanced useful syntax for grep
  • -o switch mean to print only the matching part

EDIT

If you want to put this in a variable :

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