2011-12-03 191 views
0

我的作業要求是:Shell腳本錯誤

Create a directory ~/UnixCourse/scriptAsst . Turn the two-line version, above, of the substitution commands into a shell script, subst1 taking three parameters: the string to be replaced the string with which to replace it the name of the file in which to make the substitution.

For example,

`~/UnixCourse/scriptAsst/subst1 foo bar myFile.txt` 

should replace all occurrences of foo in the file myFile.txt by bar , leaving the original file as myFile.txt.bak .

Similarly,

`~/UnixCourse/scriptAsst/subst1 abc "" aardvark.dat` 

should remove (replace by the empty string) all occurrences of abc in the file aardvark.dat with nothing, leaving the original file as aardvark.dat.bak .

,我來到了我的代碼是:

#!/bin/bash 

set p1 = "$1" 
shift 
set p2 = "$1" 
shift 
set p3 = "$*" 

echo $p1 
echo $p2 
echo $p3 

if grep "$p1" "$p3" > /dev/null; then 
mv "$p3" "$p3.bak" 
sed "s/$p1/$p2/g" "$p3.bak" > "$p3" 
fi 

當我嘗試運行:

./subst1 foo bar myFile.txt 

我不斷收到:

grep: : No such file or directory 

請幫忙!!我究竟做錯了什麼??

+1

腳本打印什麼'echo $ p1' ...? – DVK

+0

其完全空白 – Sam

+2

您是否複製並粘貼*完全*?這個錯誤看起來像是在你的'grep'命令後面有個''''。 – Kevin

回答

0

,或者使用直接的參數...

#!/bin/bash 

echo $1 
echo $2 
echo $3 

if grep "$1" "$3" > /dev/null; then 
    mv "$3" "$3.bak" 
    sed "s/$1/$2/g" "$3.bak" > "$3" 
fi 
+0

好的,這段代碼有幫助。現在我收到錯誤:subst1:找不到備份文件(測試3)。這是班上的事情,一旦我得到了這個,Ill就會與其他事物一起流動。 – Sam

+0

該代碼爲我工作...輸入文件的名稱和內容是什麼? – jlundqvist

+0

即時輸入:./subst1 foo bar myFile.txt我的測試 – Sam

1

這是你如何設置的變量:

p1="$1" 
shift 
p2="$1" 
shift 
p3="$1" 

或在這種情況下,簡單地說:

p1="$1"; p2="$2"; p3="$3" 

注:

  • 嘗試使用有意義的變量名,或者乾脆用$1直。
  • grep -q所以你不必重定向標準輸出。
+0

好的,這段代碼有幫助。現在我收到錯誤:subst1:找不到備份文件(測試3)。這是班上的事情,一旦我得到了這個,Ill就會與其他事物一起流動。 – Sam

1

你實際上並不需要做任何事情。

sed -i.bak "s/$1/$2/g" "$3"