简体   繁体   中英

awk or sed: append pattern to existing line after match

I am looking for a sed or awk solution that will insert a string into an existing line in a file after the first match of a pattern. For example I need this:

command arg arg2 -o another string and another string and so on

to look like this:

command "new string here" arg arg2 another string and another string and so on

If we match on "command" it would need to only match on the first occurrence of "command".

I prefer not to use a whole line sed substitution solution as the actual line is very long. (and there are multiple lines that I need to modify.) I have come across countless solutions on using sed or awk for appending new lines in a file or appending a string to the end or beginning of a line but have not found a solution yet to insert into the middle of a line like I need to do here.

你可以用awk实现它:

awk '$1 ~ /command/ { s = ""; for (i = 2; i <= NF; i++) s = s $i " "; print $1 " " "new string here" " " s }'

sed version:

sed -n 's/^\(command\)\(.*\)/\1 "new string here"\2/p'
  • s -- substitute
  • ^ -- beginning of line
  • () -- capture group 1
  • command -- literal string
  • () -- capture group 2
  • .* -- everything else on the line
  • \\1 -- contents of capture group 1
  • "new string here" -- literal string
  • \\2 -- capture group 2
  • p -- print it

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