0

I want to search a file for the occurrence of the word Logmon anywhere on a multi-lined file. For each row where a match is found, insert a # at the beginning of the row. I am able to accomplish this by using:

sed -i '/Logmon/ s/^/#/' nrds.cfg

The above accomplishes my objective, however, I am having issues doing this for a list of remote servers. Below is what I have so far.

#!/bin/ksh

DEST="/usr/local/nrdp/clients/nrds/"

for x in `cat /home/jack/hostlist`
do
SSH_STATUS=$(ssh -n -o BatchMode=yes -o StrictHostKeyChecking=no $USER@$x "pwd" >/dev/null)
if [[ $? = "0" ]];then
ssh -o "StrictHostKeyChecking no" $x "sudo /usr/localcw/bin/eksh -c 'cd $DEST; sed -i "/Logmon/ s/^/#/" nrds.cfg'"
else
echo "Cannot connect to $x" >> badhosts
fi
done

The above returns the following error: sed: -e expression #1, char 8: missing command

I suspect the problem is either with my quoting or I need to escape one or more of the forward slashes. I have tried numerous things and always seem to get the same error above.

1 Answer 1

1

A quoting issue. This is what happens:

"sudo /usr/localcw/bin/eksh -c 'cd $DEST; sed -i "/Logmon/ s/^/#/" nrds.cfg'"
^ double quoting starts                 ends here^    starts anew^      ends^

Because of this, sshd on the remote side runs:

sudo /usr/localcw/bin/eksh -c 'cd $DEST; sed -i /Logmon/ s/^/#/ nrds.cfg'

eksh gets:

cd $DEST; sed -i /Logmon/ s/^/#/ nrds.cfg

so now expression #1 for sed is just /Logmon/. To fix this you should escape double quotes that should get to the remote side, like this:

"sudo /usr/localcw/bin/eksh -c 'cd \"$DEST\" && sed -i \"/Logmon/ s/^/#/\" nrds.cfg'"

There are few extra improvements:

  • I also quote $DEST to ensure you get cd "<local value of $DEST>" on the remote side instead of cd <local value of $DEST>. This makes no difference in your particular case now, when the value is /usr/local/nrdp/clients/nrds/; but if you changed this path to e.g. /foo/bar baz/ then it would break your "quoteless" cd invocation.
  • && ensures sed is run only if cd succeeds (I'm not sure it works in eksh, whatever it is; it works in many shells though). If for some reason cd fails then sed won't act in your starting directory. Again this will probably never hit you, still it's a good general practice.
1
  • This is awesome !! Thanks so much Kamil and for the explanation. This works great !!
    – jackcsprat
    May 19, 2018 at 13:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .