0

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>
user3893836
  • 85
  • 10

1 Answers1

3

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'}
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Thanks for your answer. However if I add one line COUNTER_VALUE='\n'. It works. Why? – user3893836 Jul 30 '15 at 02:19
  • Because your line there **doesn't** use the `$''` ANSI C quoting to make that `\n` a *literal* newline instead of two characters. If you use `COUNTER_VALUE=$'\n'` manually you'll get the same effect as the script. – Etan Reisner Jul 30 '15 at 02:21
  • Ok, I need the carriage return. What is the best way to escape this `\n`? – user3893836 Jul 30 '15 at 02:24
  • Like I said if you need that newline in the inserted contents you need to escape it with a backslash `\\`. – Etan Reisner Jul 30 '15 at 02:27
  • Sorry, I know I need to escape the new line. However, I am not able to change source file, How should I do it? – user3893836 Jul 30 '15 at 02:43