1

From this I found the command and it works without any command substitution. But if I try to substitute a variable in the command, I get the following problems.

Note: I am using sed command(BSD OSX) / MacOS

To reproduce just create a file.txt with this:

SOME_TEXT
CHANGE_THIS
CHANGE_THIS
CHANGE_THIS

Add TMP variable in you terminal:

TMP=export PATH=/Users/Name/with pace/and_variables:$PATH

Now with this command:

sed -i '' "1h; 1 $ { x; s/CHANGE_THIS/$TMP/; p; }" file.txt

I get this error:

sed: 1: "1h; 1 $ { x; s/CHANGE_T ...": invalid command code $

In a privious answer I got this("," added to "1,$":

sed -i '' "1h; 1,$ { x; s/CHANGE_THIS/$TMP/; p; }" file.txt   

expected output file.txt

SOME_TEXT
export PATH=/Users/Name/with pace/and_variables:$PATH
CHANGE_THIS
CHANGE_THIS

I get this:

SOME_TEXT
SOME_TEXT
SOME_TEXT
SOME_TEXT
Chris G.
  • 23,930
  • 48
  • 177
  • 302
  • Why use a variable at all, when you can just paste the text directly into the sed command? If you really want to do it like this, try `"$TMP"`. – max Nov 14 '18 at 13:36

2 Answers2

1

Use:

sed -i '0,/.*CHANGE_THIS.*/s//my changed line/' file
0

Could you please try following if you are ok with awk.

##Creating shell variable named TM here.
TMP="export PATH=/Users/Name/with pace/and_variables:$PATH"
awk -v tmp="$TMP" '/CHANGE_THIS/ && ++flag==1{$0=tmp} 1' Input_file

In case you want to save output into Input_file itself then append > temp_file && mv temp_file Input_file in above code too.

Adding explanation for above code too here.

awk -v tmp="$TMP" '              ##Creating an awk variable named tmp whose value is bash variable TMP value.
/CHANGE_THIS/ && ++flag==1{      ##Checking condition if a line is having string CHANGE_THIS and variable flag value is 1 then do following.
  $0=tmp                         ##Setting current line value to value of tmp awk variable here.
}                                ##Closing the block for condition here.
1                                ##By mentioning 1 printing edited/non-edited line here.
' Input_file                     ##Mentioning Input_file name here.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93