0

I have a few bash variables and I want to replace some lines in a text file I have with only the values of these variables.

To give an artificial example.

Say I have a file named test (The numbers indicate line numbers and not text within the file.)

  1. Mary
  2. Had
  3. A Little
  4. Lamb

I want to replace line number 3 with the line 45 56. In my bash file I have stored XL=45 and XU=56 and I tried

XL=45
XU=56
sed -i '3s/.*/ $XL $XU/' test 

However this replaces the third line with $XL and $XU and not their actual values. How do I do this?

I know the obvious solution would be to replace $XL and $XU in the sed command with the actual values, but I want to replace many such lines in my long text file . So I want to define the XL and XU as variables at the top so I dont have to change my values everywhere.

2 Answers2

6

Use double quotes:

sed -i "3s/.*/ $XL $XU/" test

Single quotes prevent variable expansion.

devnull
  • 118,548
  • 33
  • 236
  • 227
5

An awk version

$ cat file
Mary
Had
A Little
Lamb

$ awk 'NR==3 {$0=l}1' l="$XL $XU" file
Mary
Had
45 56
Lamb
Jotne
  • 40,548
  • 12
  • 51
  • 55