Reputation: 37742
suppose I want to add the word "end" to each line starting with "start". However if the word "end" is already at the end of the line; no need to add it again. So how do I get from:
start line 1
start line 2 end
another line 3
start line 4
to
start line 1 end
start line 2 end
another line 3
start line 4 end
This command matches lines starting with "start", but does not exclude the lines ending with "end". How can I get a regex that does both in one line?
sed 's/\(^start.*\)/\1 end/g'
Upvotes: 1
Views: 2948
Reputation: 92854
Use the following approach:
sed -i '/ end$/! s/^start .*$/& end/' testfile
-i
option, allows to modify the file in place
/ end$/!
- allows performing the next action(substitution) only for those lines which don't end with ' end'
word
s/^start .*$/& end/
- performs the replacement only for those lines which start with start
word
If you admit the possibilities of using another good alternatives for your case, awk
could be one of them:
awk '{print ($1 == "start" && $(NF) != "end") ? $0" end" : $0}' testfile
$1
- points to the first field
$(NF)
- points to the last field
Upvotes: 1