Conditional replace using sed

时间:2016-04-04 16:37:18

标签: linux bash sed

My question is probably rather simple. I'm trying to replace sequences of strings that are at the beginning of lines in a file. For example, I would like to replace any instance of the pattern "GN" with "N" or "WR" with "R", but only if they are the first 2 characters of that line. For example, if I had a file with the following content:

WRONG
RIGHT
GNOME

I would like to transform this file to give

RONG
RIGHT
NOME

I know i can use the following to replace any instance of the above example;

sed -i 's/GN/N/g' file.txt
sed -i 's/WR/R/g' file.txt

The issue is that I want this to happen only if the above patterns are the first 2 characters in any given line. Possibly an IF statement, although i'm not sure what the condition would look like. Any pointers in the right direction would be much appreciated, thanks.

2 个答案:

答案 0 :(得分:2)

just add the circumflex, remove g suffix (unnecessary, since you want at most one replacement), you can also combine them in one script.

sed -i 's/^GN/N/;s/^WR/R/' file.txt

答案 1 :(得分:1)

Use the start-of-string regexp anchor ^:

sed -i 's/^GN/N/' file.txt
sed -i 's/^WR/R/' file.txt

Since sed is line-oriented, start-of-string == start-of-line.