2011-12-03 7 views
0

私の割り当てをエラーことを尋ねる:私が思いついたシェルスクリプトは

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

OK、このコードは役に立ちました。今私はエラーが表示されます:subst1:バックアップファイル(テスト3)を見つけることができませんでした。それはクラスのためのものです。一度これを得ると、他のものと一緒に流れます。 – 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

OK、このコードは役に立ちました。今私はエラーが表示されます:subst1:バックアップファイル(テスト3)を見つけることができませんでした。それはクラスのためのものです。一度これを得ると、他のものと一緒に流れます。 – Sam

1

あなたが実際に何もする必要はありません。

sed -i.bak "s/$1/$2/g" "$3" 
関連する問題