我有一个简单的bash查找和替换脚本'script.sh':
#!/bin/bash
find . -type f -name '.' -exec sed -i '' "s/$1/$2/" {} +
当我运行命令./script.sh foo bar时,它可以工作。假设现在我的两个输入字符串$ 1和$ 2是句子(带有空格),如何让脚本将每个字符串识别为整个字符串?
答案 0 :(得分:2)
在引号"
#!/bin/bash
echo $1
echo $2
输出
$ ./tmp.sh "first sentence" "second sentence"
first sentence
second sentence
编辑:
试试这个:
#!/bin/bash
find . -type f -exec sed -i "s/$1/$2/" {} +
输出继电器:
$ cat test1.txt
ola sdfd
$ ./tmp.sh "ola sdfd" "hello world"
$ cat test1.txt
hello world
$ ./tmp.sh "hello world" "ols asdf"
$ cat test1.txt
ols asdf
答案 1 :(得分:0)
你试过用\来屏蔽空格吗? 例如:这个\是\ sample \ string \ with \ spaces
答案 2 :(得分:0)
您只需将脚本调用为:
./myscript "sentence 1 with spaces" "sentence 2"
但你可能必须“逃避”特殊字符(或使用除sed以外的其他东西)
您可能希望将g
添加到sed s/.../.../
构造中,以便它替换同一行中的几个出现。
并且您不能在其中包含/
的字符串,因为您使用/
作为sed的分隔符。 (您可以将该分隔符更改为任何内容,例如更改为不太可能的%
:s%$1%$2%g
)