Insert text into 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 make my file like this:

ABC
MRD
DEF
GHI

I tried to do this:

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

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

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

but that didn't work either. Any suggestions?

Thank!

+3
source share
7 answers

See if this works.

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

EDIT

We can use any character instead of /. Therefore, if we expect this to be in a search or replace expression, use |

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

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

sed "/ABC/a $var"

In some older versions of sed you should write

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

ABC
<stuff>
DEF
GHI

:

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

, var - , , awk, export .

+1

; .

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

( , , $var / , sed.)

0

, , ( ) .

, s , ; , DEFMRD, MRD, . -

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

awk:

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

var :

export var=MRD
awk '{print $0}NR==1{print ENVIRON["var"]}' text.txt
0
source
printf '2i\n%s\n.\nw\n' "$var" | ed -s text.txt
0
source

All Articles