2011-12-03 166 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"