NJMR NJMR - 1 year ago 70
Bash Question

sed command in UNIX - Unable to understand

I am new to UNIX and was going through a script file and came accross a snippet.
I tried to analyze the snippet. I read a bit about the

'sed - stream editor'
command also the
sed -e
I also executed the snippet and was ablt to get see the output. But I am unable to understand whats going on. Below is the snippet.

sed -e "1,\$s/ *$/^\"`echo $ID`\"/" \

Output is

There are lots of places in the script file where they have used
command. Can someone help me how to decode these kind of snippets?

Answer Source

You should look at it part for part.

sed -e "1,\$s/ *$/^\"`echo $ID`\"/"
       |    |    |               |
         1    2          3
  1. You want to only work on specific lines. For that example start with the first line and end with the last. In this case it isn't needed to write that in this way. So

    sed -e "s/ *$/^\"$(echo $ID)\"/"

does exactly the same.

  1. Here comes the replace command. In this case you replace zero or more spaces between the last non-space and the line ending. If you want to find out more about this I suggest googling for regex.

  2. The backtick (``) is actually a 'shellism'. It causes the shell to execute the command before replacing. For a more readable way you should use $(echo $ID). After that you replace the regex from 2. with the result of this, which will be '^"101"'

And after that the result is ABCDEFGHIJK KLMJN^"101"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download