Tuesday, October 25, 2022

[SOLVED] Match a string that contains a newline using sed

Issue

I have a string like this one:

    #
    pap

which basically translates to a \t#\n\tpap and I want to replace it with:

    #
    pap
    python

which translates to \t#\n\tpap\n\tpython.

Tried this with sed in a lot of ways but it's not working maybe because sed uses new lines in a different way. I tried with:

sed -i "s/\t#\n\tpap/\t#\tpython\n\tpap/" /etc/freeradius/sites-available/default

...and many different other ways with no result. Any idea how can I do my replace in this situation?


Solution

try this line with gawk:

awk -v RS="\0" -v ORS="" '{gsub(/\t#\n\tpap/,"yourNEwString")}7' file

if you want to let sed handle new lines, you have to read the whole file first:

sed ':a;N;$!ba;s/\t#\n\tpap/NewString/g' file


Answered By - Kent
Answer Checked By - Senaida (WPSolving Volunteer)