sed: Replace word A with B from line 3 till last line only on line which contains word C

Viewed 62

Expected Input

A B C
C A B
C C A
C A A
A A B

Expected Output

A B C
C A B
C C B
C B B
A A B

Output

B B C
C B B
C C B
C B B
A A B

I am trying to make this command work but it's not working.

# '/C/s/A/B' file > newfile
sed '3,$ /C/s/A/B' file > newfile
3 Answers

You will beed to use { ...; } to group sed commands for the line ranges you want and put a ; before } so make sure BSD/POSIX sed can work with that.

You may use this sed:

sed '3,$ { /C/ s/A/B/g; }' file > newfile

cat > newfile


A B C
C A B
C C B
C B B
A A B

With your shown samples, please try following awk code. Simple explanation would be, checking condition if line number is more than 3 or equal to 3 AND line contains C then globally substitute all occurrences of A with B and print edited/non-edited lines.

awk 'FNR>=3 && /C/{gsub(/A/,"B")} 1' Input_file

This might work for you (GNU sed):

sed '3,$!b;/C/y/A/B/' file

If the line number is not between 3 and the end-of-the-file, bail out.

Otherwise, for lines containing C, translate A's to B's.

N.B. If A's and B's are true words, use s/A/B/g.

Related