Friday, January 26, 2024

[SOLVED] add a comment on a line above a searched line in shell script

Issue

Suppose below is a text file

abcd
abc:

I want to search for abc: and add # in front of abcd

OUTPUT

#abcd
abc:

I tried using

sed -e '/abc/ s/^#*/#/' -i file

but unable to do the above action.


Solution

Since you are editing in-place, you can use ed:

printf '%s\n' '/abc:/-1 s/^/#/' w q | ed -s file

With POSIX sed it is more tricky. One possibility is:

sed -i '
    N
    /abc:/ {
        s/^/#/
        :a
        n
        ba
    }
    P
    D
' file

Both scripts assume that abc: cannot appear on the first line of the file, and that you wish to change only the line above the first occurrence of the pattern even if it appears multiple times.



Answered By - jhnc
Answer Checked By - Cary Denson (WPSolving Admin)