unifactor
unifactor

Reputation: 15

Write a shell script that replaces multiple strings in multiple files

I need to search through many files in a directory for a list of keywords and add a prefix to all of them. For example, if various files in my directory contained the terms foo, bar, and baz, I would need to change all instances of these terms to: prefix_foo, prefix_bar, and prefix_baz.

I'd like to write a shell script to do this so I can avoid doing the search one keyword at a time in SublimeText (there are a lot of them). Unfortunately, my shell-fu is not that strong.

So far, following this advice, I have created a file called "replace.sed" with all of the terms formatted like this:

s/foo/prefix_foo/g
s/bar/prefix_bar/g
s/baz/prefix_baz/g

The terminal command it suggests to use with this list is:

sed -f replace.sed < old.txt > new.txt

I was able to adapt this to replace instances within the file (instead of creating a new file) by setting up the following script, which I called inline.sh:

#!/bin/sh -e
in=${1?No input file specified}
mv $in ${bak=.$in.bak}
shift
"$@" < $bak > $in

Putting it all together, I ended up with this command:

~/inline.sh old.txt sed -f replace.sed

I tried this and it works, for one file at a time. How would I adapt this to search and replace through all of the files in my entire directory?

Upvotes: 1

Views: 79

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295403

for f in *; do
  [[ -f "$f" ]] && ~/inline.sh "$f" sed -f ~/replace.sed
done

Upvotes: 2

economy
economy

Reputation: 4251

In a script:

#!/bin/bash
files=`ls -1 your_directory | egrep keyword`

for i in ${files[@]}; do
    cp ${i} prefix_${i}
done

This will, of course, leave the originals where they are.

Upvotes: 1

Related Questions