简体   繁体   中英

fIm trying to find a string betwen two match patterns and then add that string before a pattern using sed

Say I have the below line in file named "logs_test":

Sample input:

"at 10947 usecs after Tue Feb 23 18:29:46 2021 [119] init: Event=populatedonRestart"

I wanted to find a string between "at" and "usecs" and add the string before "2021" in the above line

sample output:

"at 10947 usecs after Tue Feb 23 18:29:46 10947 2021 [119] init: Event=populatedonRestart"

sed command to find a string between two matching patterns:

sed "s/at//;s/usecs.*//“ <file_name>

sed command to add a string before a pattern:

sed 's/2021/string &/g' <file_name>

How can I accomplish two tasks using one sed command? Is there were to use the sed command inside sed to do this?

This will do it for your example (with GNU sed):

sed 's/^\(at \)\(.* \)\(usecs.*\)\(2021.*\)/\1\2\3\2\4/' your_file

The ways it's working is as follows:

  • I remember the stuff in between \( and \) (these are called capture groups)
  • I break the string into 4 capture groups, the 2nd capture group is the number you care about. And I put the groups back together and use the 2nd capture group twice: /\1\2\3\2\4/

Once you've confirmed it does what you want, you could add the -i to do the replacement in-place:

sed -i 's/^\(at \)\(.* \)\(usecs.*\)\(2021.*\)/\1\2\3\2\4/' your_file

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