Saturday, 21 November 2015

Bash - Using Variables in Sed

Set a variable

export NAME=DAVID

Validate the variable

echo $NAME

DAVID

Initialise a file

echo "DAVE" > foobar.txt

Validate the file contents

cat foobar.txt

DAVE

Replace the contents of the file with the contents of the variable

sed -i'' "s/DAVE/$NAME/g" foobar.txt

Validate the file contents

cat foobar.txt

DAVID

This works with Bash 4.1.2(1)-release on RHEL 6.6.

No comments: