Simple 'sed' script for replacing text

Hi All,

So I found a simple sed command to replace text in a file (http://www.labnol.org/internet/design/wordpress-unix-replace-text-multiple-files/1128/\):

sed -e 's/OLDtext/NEWtext/' -i file(s)

Because I'm lazy and don't want to remember this each time I want to do this, I wrote the following simple script (rptxt.sh):

#! /bin/bash
sed -e 's/$1/$2/' -i $3

My intention was to make it a commandline program,

rptxt OLDtext NEWtext file(s)

.
However when I run this it does replace the text and only looks in the first file (if multiple files are entered such as *.txt). Any ideas why, and how it can be fixed? Thanks.

Cheers,
ScKaSx

You would need to use some sort of iteration.

For example:

for $i in `ls -A *.txt` do (rptxt foo bar) done

Note: I did not run that command. You may have to modify the syntax a bit.

That script would not replace anything but a literal $1, and it would replace it with a literal $2. And (after replacing the single quotes with double quotes) it will only work with GNU sed. And it will break if $3 contains a space or wildcard character. Or if either $1 or $2 contains a slash.

#!/bin/bash
search=${1//\//\\/}
replace=${2//\//\\/}
shift 2
sed -i "s/$search/$replace/g" "$@"

Thanks guys,

cfajohnson your script works great. Now i understand that I was just passing literals rather than variables. I just have two questions about the rest of the script:

(1) what does 'shift' do?
(2) how come $@ as opposed to $3?

Thanks!

Cheers,
ScKaSx

$ help shift
shift: shift [n]
    The positional parameters from $N+1 ... are renamed to $1 ...
    If N is not given, it is assumed to be 1.

Because you wanted to operate on more than one file. "$3" is a single argument; "$@" is all the arguments.

1 Like