2013-01-31 23 views
0

我有一個簡單的bash查找和替換腳本「script.sh」:腳本和空格

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

當我運行我的命令./script.sh foo的酒吧,它的工作原理。假設現在我的兩個輸入字符串$ 1和$ 2是句子(帶有空格),我怎樣才能讓腳本識別每個字符串爲整個字符串?

回答

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

是的,但現在查找和替換腳本不再工作... – user1611830

+0

試試這個......爲什麼它不起作用? – user000001

+0

嘗試這裏現在我的輸出sed:1:「./.DS_Store」:無效的命令代碼。 – user1611830

0

你試過用\屏幕空格嗎? 例如:This \是\樣本\字符串\與\空間

+0

它似乎確實改正了輸入,但現在查找和替換腳本不再工作了...... – user1611830

0

你只需要打電話給你的腳本:

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

但是你可能不得不「逃離」特殊字符(或用別的比sed)

您可能需要將g添加到sed s/.../.../結構中,以便它可以替換同一行上的多個匹配項。

而且您不能使用其中/的字符串,因爲您使用/作爲sed的分隔符。 (您可以更改該分隔符爲任何東西,例如對不太可能的%s%$1%$2%g

+0

您的意思是將「s/$ 1/$ 2 /」更改爲s%$ 1%$ 2%g?我做了,但劇本並沒有發現也沒有取代 – user1611830