1

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?

3 Answers 3

1

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"
0

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"
2
  • Thanks for the answer. I tried your method and it seemed to work. Is there any way this behavior can automated inside of a script? Commented Dec 8, 2013 at 19:31
  • Make sure you enclose any file name references inside double quotes. The globbing notation (*.txt etc) can't be in quotes, but any time you have a variable $file that you're referencing, make sure the reference is in double quotes: cat "$file" etc. Commented Dec 8, 2013 at 20:16
0

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 $*
1
  • "I don't have access to bash at the weekend"
    – dibs
    Commented Feb 17, 2017 at 1:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.