user754905
user754905

Reputation: 1809

Inserting text in a file from a variable

I have a file that looks something like this:

ABC
DEF
GHI

I have a shell variable that looks something like this:

var="MRD"

What I want to do, is to make my file look like this:

ABC
MRD
DEF
GHI

I was trying to do this:

sed -i -e 's/ABC/&$var/g' text.txt 

but it only inserts $var instead of the value. I also tried this:

sed -i -e 's/ABC/&"$var"/g' text.txt 

but that didn't work either. Any thoughts?

Thanks!

Upvotes: 3

Views: 205

Answers (7)

Mark Edgar
Mark Edgar

Reputation: 4827

printf '2i\n%s\n.\nw\n' "$var" | ed -s text.txt

Upvotes: 0

amit_g
amit_g

Reputation: 31260

See if this works.

var="MRD"
sed 's/ABC/&\n'"${var}"'/' text.txt

EDIT

We can use any character instead of /. So if we expect it to be in the search or replace expression, use |

var="</stuff>"
sed 's|ABC|&\n'"${var}"'|' text.txt

Upvotes: 3

Charles Duffy
Charles Duffy

Reputation: 295650

var='<stuff>' awk '{ print $0 } NR==1 { print ENVIRON["var"]; }' \
  <<<$'ABC\nDEF\nGHI' \

yields

ABC
<stuff>
DEF
GHI

To do an in-place replacement:

tempfile=$(mktemp "${infile}.XXXXXX")
awk ... <"$infile" >"$tempfile" \
  && mv "$tempfile" "$infile"

Note that var needs to be in the environment -- so if you aren't defining it on the same line where you invoke awk, you should export it.

Upvotes: 1

icyrock.com
icyrock.com

Reputation: 28618

With awk:

awk "{print \$0}NR==1{print \"$var\"}" text.txt

or if var has been exported:

export var=MRD
awk '{print $0}NR==1{print ENVIRON["var"]}' text.txt

Upvotes: 0

geekosaur
geekosaur

Reputation: 61449

You need to terminate the single quotes (which prevent interpolation) before you can switch to the double quotes, or just use double quotes to start with.

That said, the s command changes the current line, it does not insert lines; you would end up with a single line containing DEFMRD, not MRD inserted on its own line. For that, you want something like

sed -i -e "/ABC/a\\
$var\\
." text.txt

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247012

sed can do more than search and replace -- it can append:

sed "/ABC/a $var"

In some older versions of sed, you have to write

sed "/ABC/a\\
$var"

Upvotes: 2

jwodder
jwodder

Reputation: 57590

Single quotes disable variable interpolation; double quotes do not.

sed -i -e "s/ABC/&$var/g" text.txt

(Note that this isn't such a good idea when $var contains / or any other character that sed treats specially.)

Upvotes: 0

Related Questions