Reputation: 71
I have a shell script that takes 3 parameters and performs text substitutions based on those parameters. The first parameter is the text to be replaced, the second is the text to replace it with, and the third is the file name. The script works unless the file name has a space. I am not sure how to get sed to parse the filename, and not break it into two files. The current version of the script is as follows:
#! /bin/sh
oldString=$1
newString=$2
file=$3
oldStringFixed=$( echo "$oldString" | sed -e "s/\("\''[]*^+\.$[-]\)/\\\1/g' )
sed -e "s/$oldStringFixed/$newString/g" "$file"> newfile.updated
mv newfile.updated "$file"
When invoked like:
./script replacethis withthis on this.txt
the name on this.txt
is broken into two. Can anyone explain how to deal with files that have spaces in their names?
Upvotes: 1
Views: 1815
Reputation: 4025
I can't test this, as I don't have access to bash at the weekend, but try
oldString=$1
newString=$2
shift 2
file="$*"
echo $*
Upvotes: 0
Reputation: 754710
The main problem is in the invocation, not the script. You need to enclose the name in quotes so that the shell sees it as a single argument:
./script replacethis withthis "on this.txt"
Upvotes: 0
Reputation: 141918
Quote the filename with spaces on the command-line, just like you do in your script:
./script replacethis withthis "on this.txt"
You could even specify multiple words for oldString
and newString
:
./script "replace this" "with that" "on this.txt"
Upvotes: 1