Skip to content
Advertisement

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 .

JavaScript

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

JavaScript

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

Advertisement

Answer

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

JavaScript

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

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement