Dinesh Kumar Dinesh Kumar -4 years ago 118
Linux Question

Linux: Append variable to end of line using line number as variable

I am new to shell scripting. I am using ksh.

I have this particular line in my script which I use to append text in a variable

q
to the end of a particular line given by the variable
a

containing the line number .

sed -i ''$a's@$@'"$q"'@' test.txt


Now the variable
q
can contain a large amount of text, with all sorts of special characters, such as !@#$%^&*()_+:"<>.,/;'[]= etc etc, no exceptions.
For now, I use a couple of sed commands in my script to remove any ' and " in this text (
sed "s/'/ /g" | sed 's/"/ /g'
), but still when I execute the above command I get the following error


sed: -e expression #1, char 168: unterminated `s' command


Any sed, awk, perl, suggestions are very much appreciated

Answer Source

The difficulty here is to quote (escape) the substitution separator characters @ in the sed command:

sed -i ''$a's@$@'"$q"'@' test.txt

For example, if q contains @ it will not work. The @ will terminate the replacement pattern prematurely. Example: q='a@b', a=2, and the command expands to

sed -i 2s@$@a@b@ test.txt

which will not append a@b to the end of line 2, but rather a@.

This can be solved by escaping the @ characters in q:

sed -i 2s@$@a\@b@ test.txt

However, this escaping could be cumbersome to do in shell. Another approach is to use another level of indirection. Here is an example of using a Perl one-liner. First q is passed to the script in quoted form. Then, within the script the variable assigned to a new internal variable $q. Using this approach there is no need to escape the substitution separator characters:

perl -pi -E 'BEGIN {$q = shift; $a = shift} s/$/$q/ if $. == $a' "$q" "$a" test.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download