質問

Homework - don't just throw me an answer, but I've literally been stuck on this for days. That also explains why I'm stuck using csh, which is of course exacerbating the problem.

The shell script needs to search a file for a string and replace it with a new string, creating a backup file if the string has been found and the file has been altered. Simple enough, right?

Here's my code.

    #!/bin/csh                                                                     
set currentWord=$1
set newWord=$2
set fileName=$3

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

  if  (grep -q $1 $3)  then
     sed -i.bak -e "s/$1/$2/g" $3
   else
     echo "The string is not found."
   endif

The problem I'm running into is that it's not supposed to "touch" the file unless the string is found. The way I've been doing it creates the file either way, sometimes they just end up being identical files. I've tried by only using one sed command as well, but the closest I've gotten to the solution is by working the sed command into an if then else. Now I'm getting an "if expression syntax" error - which is making me think I can't use grep like that at all and need to reformat it or use something else.

役に立ちましたか?

解決

You need to check the exit status of grep. And there are a couple of ways to do so.

You either:

call grep and then examine the special variable $status, like in

#!/bin/csh

set currentWord=$1
set newWord=$2
set fileName=$3

grep -q $currentWord $fileName

if !($status) then
    sed -i.bak -e "s/$currentWord/$newWord/g" $fileName
else
    echo "The string is not found."
endif

or, since the actual vale of $status is not needed here, just use the terser form

#!/bin/csh

set currentWord=$1
set newWord=$2
set fileName=$3

if { grep -q $currentWord $fileName } then
    sed -i.bak -e "s/$currentWord/$newWord/g" $fileName
else
    echo "The string is not found."
endif

The second one is my favourite.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top