I have a ksh script, which I have problem in insert few lines with carriage into a file.
#!/bin/ksh
FILE_NAME="/tmp/t.xml"
LINE="<moid>ManagedElement=1,Equipment=1,Subrack=MAIN,Slot=3,PlugInUnit=1</moid>"
COUNTER_VALUE=`grep -A4 $LINE $FILE_NAME | sed -e '/-/,\$d' | grep '<r>`
sed "1i$COUNTER_VALUE" $FILE_NAME
Ksh debug log asb below.
aaa[678] /tmp$ ksh -x ./t.ksh
+ FILE_NAME=/tmp/t.xml
+ LINE='<moid>ManagedElement=1,Equipment=1,Subrack=MAIN,Slot=3,PlugInUnit=1</moid>'
+ grep -A4 '<moid>ManagedElement=1,Equipment=1,Subrack=MAIN,Slot=3,PlugInUnit=1</moid>' /tmp/t.xml
+ grep '<r>'
+ sed -e '/-/,$d'
+ COUNTER_VALUE=$'<r></r>\n<r></r>'
+ sed $'1i<r></r>\n<r></r>' /tmp/t.xml
sed: -e expression #1, char 11: unknown command: `<'
My question is what is the first Dollar symbol in the variable COUNTER_VALUE. I actually want to have COUNTER_VALUE as below.
COUNTER_VALUE='<r></r>\n<r></r>'
which keep carriage return and do not have annoying dollar symbol. This special dollar create problem in my sed command.
Please help.
Contents of file t.xml as below.
<gp>900</gp>
<mt>pmSwitchIngressDiscards</mt>
<mt>pmSwitchIngressLoad</mt>
<mv>
<moid>ManagedElement=1,Equipment=1,Subrack=MAIN,Slot=3,PlugInUnit=1</moid>
<r></r>
<r></r>
</mv>
<mv>
The $
in COUNTER_VALUE=$'<r></r>\n<r></r>'
is not actually there.
That's -x
showing you that the \n
in that string is a literal newline and not the two characters \
and n
.
That embedded newline is the problem. With it there sed sees 1i<r></r>
as one command and then <r></r>
as a second command.
You need to remove and/or escape that newline to make this work.
You can escape it with:
COUNTER=${COUNTER//$'\n'/$'\\\n'}