简体   繁体   中英

using sed to substitute a string

I have a line like this :

 22.665774 Fr RMSG  0 0 1 1 18 11 Rx 0 308002 5  20  1d6 x 20 20 a8 4f 35 40 1b 00 0f 08 f7 89 ff fa ff f3 35 80 49 00 00 00 00 30 00 00 80 ab 4b 54 40 f0 00 fc 714a81  1  40937

I want to parse it and substitute it in such a way to get only this part :

a8 4f 35 40 1b 00 0f 08 f7 89 ff fa ff f3 35 80 49 00 00 00 00 30 00 00 80 ab 4b 54 40 f0 00 fc

At this moment i am using this :

sed -re \"s/^.+x//\

But this only gives me the part before x.. can you give me some hints please?

Thanks .

You can use this regular expression:

\sx\s(?:[0-9a-f]{2}\s){2}(.*?)\s\w{3,}

This will return the part you want in a caught group. Tested here .

Does it have to be sed? cut does it perfectly.

echo '22.665774 Fr RMSG  0 0 1 1 18 11 Rx 0 308002 5  20  1d6 x 20 20 a8 4f 35 40 1b 00 0f 08 f7 89 ff fa ff f3 35 80 49 00 00 00 00 30 00 00 80 ab 4b 54 40 f0 00 fc 714a81  1  40937' | cut -d' ' -f22-53

You can use this expression to match the whole line and capture the strings aftex x <hex> <hex> :

.*?\sx\s\w*?\s\w*?\s(.*?)\s\w{4,}.*

This assumes the x is always the delimiter where you want to cut off the remainder of the string.

Edit :

Full command to do this on the command line:

echo " 22.665774 Fr RMSG  0 0 1 1 18 11 Rx 0 308002 5  20  1d6 x 20 20 a8 4f 35 40 1b 00 0f 08 f7 89 ff fa ff f3 35 80 49 00 00 00 00 30 00 00 80 ab 4b 54 40 f0 00 fc 714a81  1  40937" | perl -pe "s/.*?\sx\s\w*?\s\w*?\s(.*?)\s\w{4,}.*/\1/"

I'm not familiar with sed but this applies in the general regex case:

This regex will match the string "a8 ... fc" where "..." can be any combination of hex-bytes (only lower case letters) and spaces:

/a8([0-9a-f ]+)fc/

You can then use substitution in the same regex using:

/a8$1fc/

Here $1 will be substituted with the match in between the parentheses ([0-9a-f ]+) .

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