简体   繁体   English

脚本和空格

[英]Scripts and white spaces

I have a simple bash find and replace script 'script.sh' : 我有一个简单的bash查找和替换脚本'script.sh':

#!/bin/bash 
find . -type f -name '.' -exec sed -i '' "s/$1/$2/" {} +

When I run my command ./script.sh foo bar, it works. 当我运行我的命令./script.sh foo bar时,它可以工作。 Suppose now my two inputs strings $1 and $2 are sentences (with white spaces), how can I make the script to recognize each of them as whole strings ? 假设现在我的两个输入字符串$ 1和$ 2是句子(带有空格),我怎样才能使脚本将每个字符串识别为整个字符串?

Add each sentence in quotes " 在引号中添加每个句子"

#!/bin/bash
echo $1
echo $2

output 产量

$ ./tmp.sh "first sentence" "second sentence"
first sentence
second sentence

Edit: 编辑:

Try this: 尝试这个:

#!/bin/bash
find . -type f -exec sed -i "s/$1/$2/" {} +

Ouput: 输出继电器:

$ 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

have you tried to screen spaces with \\? 你有没有试过用\\?屏幕空间? eg: this\\ is\\ sample\\ string\\ with\\ spaces 例如:这个\\是\\ sample \\ string \\ with \\ spaces

You just need to call your script as : 您只需将脚本调用为:

./myscript  "sentence 1 with spaces" "sentence 2"

But you may have to "escape" special characters (or use something else than sed) 但你可能必须“逃避”特殊字符(或使用除sed之外的其他东西)

You may want to add g to the sed s/.../.../ construct so that it replaces several occurence on the same line. 您可能希望将g添加到sed s/.../.../构造中,以便它替换同一行上的几个出现。

And you can't have a string with a / in it, as you use / as the sed's separator. 并且你不能使用带有/的字符串,因为你使用/作为sed的分隔符。 (You can change that separator to anything, for example to the unlikely % : s%$1%$2%g ) (您可以将该分隔符更改为任何内容,例如更改为不太可能的%s%$1%$2%g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM