Jimmy
Jimmy

Reputation: 12517

Find and replace in bash for variables

I am using bash and I was wondering if there is a nice way to do a find and replace on a file using bash. In my case I want to turn a placeholder variable into the orignal variable, working with any number of different variables. For example:

"$PLACEHOLDER_ABC" -> $ABC 
"$PLACEHOLDER_123" -> $123 
"$PLACEHOLDER_qwe" -> $qwe

I am not sure where to start, should I be using find, sed, a while loop, or all of the above?

Upvotes: 0

Views: 750

Answers (3)

Anitha Mani
Anitha Mani

Reputation: 867

find filename -exec sed -i 's/\$PLACEHOLDER_/\$/g' {} \;

Upvotes: 0

chepner
chepner

Reputation: 532303

Something like

sed 's/\$PLACEHOLDER_/\$/g' file

would remove PLACEHOLDER_ everywhere it is found after a dollar sign, effectively truncating the parameter expansion where it occurs.

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 208003

You may want to have a look at "m4" the macro processor. The manpages are here. It is included in most Linux/Unix distros.

Here is a little example:

define(`hello', `Hello, World')
hello, welcome to m4!

If we run this file through m4 with the command

m4 sample.m4 > sample.txt

it produces the following output:

Hello, World, welcome to m4!

Upvotes: 0

Related Questions