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.
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" "$@"
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?