Sunday, January 28, 2024

[SOLVED] Insert a line after current line if line before it matches some pattern using sed ;

Issue

I'm looking for a sed command to add instruction after a line matching pattern if line before it contains some string too. Hard to tell so here's the input :

if [ $coderet -ne 0 ];then
#  $UXEXE/uxset msg "*** KO *** voir log systeme ***"
exit 1
fi

if [ $coderet -ne 0 ];
  then
#  $UXEXE/uxset msg "*** KO *** voir log systeme ***"
exit 1
fi

I want to add echo "" after line that matches # $UXEXE/uxset msg if line before it contains string then so expected result would look like :

if [ $coderet -ne 0 ];then
#  $UXEXE/uxset msg "*** KO *** voir log systeme ***"
  echo ""
  exit 1
fi

if [ $coderet -ne 0 ];
  then
#  $UXEXE/uxset msg "*** KO *** voir log systeme ***"
  echo ""
  exit 1
fi

Thanks in advance for your help!

I tried several things without much result! Sorry!


Solution

A solution in awk is straightforward:

awk '{
    print
    if (prev_had_then && index($0, "#  $UXEXE/uxset msg"))
        print "  echo \"\""
    prev_had_then = /then/
}' file

sed is not much more complex:

sed '
    /then/ {
        N
        /#  \$UXEXE\/uxset msg/ a\
  echo ""
    }
' file


Answered By - jhnc
Answer Checked By - Candace Johnson (WPSolving Volunteer)