Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为shell脚本处理文件名中的空格_Shell_Sed_Filenames - Fatal编程技术网

为shell脚本处理文件名中的空格

为shell脚本处理文件名中的空格,shell,sed,filenames,Shell,Sed,Filenames,我有一个shell脚本,它接受3个参数并基于这些参数执行文本替换。第一个参数是要替换的文本,第二个参数是要替换的文本,第三个参数是文件名。除非文件名有空格,否则脚本将正常工作。我不知道如何让sed解析文件名,而不是将其分成两个文件。脚本的当前版本如下所示: #! /bin/sh oldString=$1 newString=$2 file=$3 oldStringFixed=$( echo "$oldString" | sed -e "s/\("\''[]*^+\.$[-]\)/\\\1/g'

我有一个shell脚本,它接受3个参数并基于这些参数执行文本替换。第一个参数是要替换的文本,第二个参数是要替换的文本,第三个参数是文件名。除非文件名有空格,否则脚本将正常工作。我不知道如何让sed解析文件名,而不是将其分成两个文件。脚本的当前版本如下所示:

#! /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"
调用时,如:

./script replacethis withthis on this.txt

这个.txt上的名称
被分成两部分。谁能解释一下如何处理名称中有空格的文件吗?

在命令行中用空格引用文件名,就像在脚本中一样:

./script replacethis withthis "on this.txt"
您甚至可以为
oldString
newString
指定多个单词:

./script "replace this" "with that" "on this.txt"

在命令行中用空格引用文件名,就像在脚本中一样:

./script replacethis withthis "on this.txt"
您甚至可以为
oldString
newString
指定多个单词:

./script "replace this" "with that" "on this.txt"

主要问题在于调用,而不是脚本。您需要将名称括在引号中,以便shell将其视为单个参数:

./script replacethis withthis "on this.txt"

主要问题在于调用,而不是脚本。您需要将名称括在引号中,以便shell将其视为单个参数:

./script replacethis withthis "on this.txt"

我不能测试这个,因为我周末没有访问bash的权限,但是试试看

oldString=$1
newString=$2
shift 2
file="$*"
echo $*

我不能测试这个,因为我周末没有访问bash的权限,但是试试看

oldString=$1
newString=$2
shift 2
file="$*"
echo $*

谢谢你的回答。我试过你的方法,它似乎奏效了。有没有办法在脚本中自动执行此行为?请确保将所有文件名引用括在双引号内。全局标记(
*.txt
等)不能用引号括起来,但任何时候当您引用变量
$file
时,请确保引用是用双引号括起来的:
cat“$file”
等。谢谢您的回答。我试过你的方法,它似乎奏效了。有没有办法在脚本中自动执行此行为?请确保将所有文件名引用括在双引号内。globbing符号(
*.txt
等)不能用引号括起来,但任何时候当您引用变量
$file
时,请确保引用是用双引号括起来的:
cat“$file”
等。“我周末没有访问bash的权限”“我周末没有访问bash的权限”