LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   sed command using variable (http://www.linuxquestions.org/questions/linux-newbie-8/sed-command-using-variable-4175440276/)

nwalsh88 12-06-2012 09:02 AM

sed command using variable
 
Hi All,

I am trying to run a sed command to add a variable to certain position on a line of a file.

file is below (trailerfile)

TOT_______________________________________________________________________________________________To tal EUR0000000000001568.50

i have a variable called total which is already defined as a numeric value (0000000000001582.18)

the command im using is:
sed 's:\(.\{107\}\)\(.\{19\}\):\1$total:' trailerfile

but its returning:
TOT_______________________________________________________________________________________________To tal EUR$total


any advice how to make 0000000000001582.18 appear instead of $total?

druuna 12-06-2012 09:11 AM

Using single quotes will tell the shell not to expand the variable.

2 solutions: use double quotes:
Code:

sed "s/\(.*EUR\).*/\1$total/" infile
or using single quotes:
Code:

sed 's/\(.*EUR\).*/\1'$total'/' infile

David the H. 12-06-2012 01:53 PM

1) Please use ***[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.

The long, unbroken lines in your post are forcing my screen to side-scroll. Edit it to enclose them, please.

2) Please try doing a search of past threads first. Questions like this tend to come up with good regularity.


In any case, this is a common example of how important it is to understand the shell's quoting behavior and argument parsing.

http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes


3) You can avoid most of those backslashes if you enable the -r extended regular expressions option.

Code:

sed -r "s:(.{107})(.{19}):\1$total:" trailerfile
See the section on basic versus extended regex in the sed info page.


All times are GMT -5. The time now is 03:01 AM.