Issue
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
Solution
You can use
sed -i.bkp '/start/{:a;N;/end/!s/$/</;/end/!ba;}' test.txt
Details:
/start/
- matches a line containingstart
and then executes the subsequent block of commands...:a
- sets ana
labelN
- reads the next line appending it to pattern space/end/!
- if there is noend
in the current pattern space...s/$/</
- replace end of string position with<
(adds<
at the end of the pattern space)/end/!ba
- if there isend
stop processing block, else, go toa
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
Answered By - Wiktor Stribiżew Answer Checked By - Katrina (WPSolving Volunteer)