简体   繁体   中英

How to extract string between a pattern and a position from the pattern with Tshark and sed

The problem I have cosist in: With Tshark and sed I can obtain the rtp-stream in hex dump. Is it possible to obtain only the byte between a pattern and a position after the pattern. I provide an example: In cmd... Tshark -x -r "C:whatever\\file.pcap" -Y "rtp and frame.len==1200" | sed ¿¿¿???

How should I write the regular expression in sed? The pattern is '47 00 11 1*' and the position after the pattern is two and three. For instance: 09 9f 5a 47 00 11 18 ce ff ff. The point would be obtain 'ce'.

Thank you very much for you assistance!

To be clear, the focus of this question is regex, and sed is one tool that uses regex (other bash ones being grep and awk). sed also differs between linux and macos; here I'm using GNU sed which you are likely using as well.

We'll use sed as that is part of the question statement.

The Regex

This is your regex: 47 00 11 1..(..) . The 47 00 11 1 matches these characters exactly. .. will match any 2 characters. (..) will capture the 2 characters after, whatever they are. The parentheses form the capturing group and are important because they return only the string we care about.

To play around with regexes, I recommend using regex101. You can explore this specific regex and test case on regex101 here .

Piping to Sed

Your question uses sed, so this would be

bash-5.0$ echo "09 9f 5a 47 00 11 18 ce ff ff" | sed -n 's/.*47 00 11 1..\(..\).*/\1/p'
ce

Here, the regex is the same apart from sed requirements:

  • .* : .* matches any number of characters. Adding it to beginning and end will match the string exactly.
  • \\( , \\) : sed requires escaping parentheses to denote capture groups

Other components are as follows:

  • -n : Be quiet about internal processing of pattern
  • s/ : Substitute the string provided with the capture group
  • \\1 : Replace with capture group 1
  • /p : Print the result (used in conjunction with /s at the beginning)

Note : Many languages like Perl support a regex standard called PCRE ( P erl C ompatible R egular E xpressions), which is easier to use than sed syntax. In my experience, using Perl or Python inline for regexes makes your life easier than using sed (or grep or awk).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM