how to append a line with sed/awk after specific t

2020-05-01 09:12发布

问题:

i would like to translate this input file using sed or awk:

input
1 AA
3 BB
5 CC

output
1 AA
3 BB
3 GG
5 CC

the closest syntax I found on this site sed -i '/^BB:/ s/$/ GG/' file but it does 3 BB GG. What I need is similar to a vi yank, paste & regex replace. can this be done with sed or awk? thanks Rand

回答1:

awk is a fine choice for this:

awk '{print $0} $2=="BB"{print $1,"GG"}' yourfile.txt

That will print the line {print $0}. And then if the second field in the line is equal to "BB", it will print the first field in the line (the number) and the text "GG".

Example in use:

>echo "1 AA\n3 BB\n4 RR" | awk '{print $0} $2=="BB"{print $1,"GG"}'
1 AA
3 BB
3 GG
4 RR


回答2:

With GNU sed:

sed -r 's/^([^ ]*) BB$/&\n\1 GG/' file

Output:

1 AA
3 BB
3 GG
5 CC


回答3:

This might work for you (GNU sed):

sed '/BB/p;s//GG/' file

If the line contains the required string print it then substitute another string for it.



回答4:

In awk:

$ awk '1; /BB/ && $2="GG"' input
1 AA
3 BB
3 GG
5 CC

1 prints the record. If there was BB in the record just printed, replace it with GG and print again.



标签: awk sed