Reputation: 169
Here is my file (test.txt):
start
line1
line2
line3
end
I want to search all the lines between the patterns start and end and then append "<" at the end of the searched lines. The final output should be (need an inline replacement in the same file):
start
line1<
line2<
line3<
end
I also want to do an inline replacement in the same file. Here is what I have done till now.
sed -n '/start/,/end/{/start/!{/end/!p;};}' test.txt
This gives me the below output:
line1
line2
line3
But I don't know how I can do the inline replacement in the same line. I tried this but it does not work.
sed -n -i.bkp '/start/,/end/{/start/!{/end/!p;};}; s/$/</' test.txt
Upvotes: 1
Views: 395
Reputation: 58528
This might work for you (GNU sed):
sed -i '/start/,/end/{//b;s/$/</}' file
Select the range between start
and end
and if it is neither of the two regexps denoting the range, append <
to the end of each line.
Upvotes: 2
Reputation: 627344
You can use
sed -i.bkp '/start/{:a;N;/end/!s/$/</;/end/!ba;}' test.txt
Details:
/start/
- matches a line containing start
and then executes the subsequent block of commands...
:a
- sets an a
labelN
- reads the next line appending it to pattern space/end/!
- if there is no end
in the current pattern space...s/$/</
- replace end of string position with <
(adds <
at the end of the pattern space)/end/!ba
- if there is end
stop processing block, else, go to a
label.See the online demo:
#!/bin/bash
s='start
line1
line2
line3
end'
sed '/start/{:a;N;/end/!s/$/</;/end/!ba;}' <<< "$s"
Output:
start
line1<
line2<
line3<
end
Upvotes: 1