How to use 'sed' with piping

I want to replace a string outputted from grep, I have:

$ npm info webpack | grep version 

it outputs me

$ version: '2.1.0-beta.12',

but I want to have:

$ 2.1.0-beta.12

So I think I might achieve that using sed and replace unnecessary substrings. But here goes the hard part for me:

$ npm info webpack | grep version: | sed s/version: /
sed: -e expression #1, char 10: unterminated `s' command

How can achieve my goal?


Solution 1:

If you are going to use sed, there is no need to also use grep. Try:

npm info webpack | sed -En "s/version: '(.*)',/\1/p"

Example:

$ echo  "version: '2.1.0-beta.12'," | sed -En "s/version: '(.*)',/\1/p"
2.1.0-beta.12

Alternative: using awk

Similarly, if we use awk, there is no need to also grep:

npm info webpack | awk -F"[ ',]+" '/version:/{print $2}'

Example:

$ echo  "version: '2.1.0-beta.12'," | awk -F"[ ',]+" '/version:/{print $2}'
2.1.0-beta.12

How it works:

  • -F"[ ',]+"

    This tells awk to use spaces, single quotes, or commas or any combination thereof as field separators.

  • /version:/{print $2}

    If a line contains version:, then print the second field.

Solution 2:

The sed substitute command (s) expects a search pattern and a replacement string. You only supplied it with a search pattern. You also should quote strings properly in the shell:

$ npm info webpack | grep 'version:' | sed 's/version: //'

This will give you the result '2.1.0-beta.12',, which is not quite what you want.

Since the output from grep is so simple, you may use cut with the delimiter ' to get the second field of the line (without the need for complicated regular expressions):

$ npm info webpack | grep -F 'version:' | cut -d "'" -f 2

This will give you 2.1.0-beta.12.

I also added -F to grep since the string you search for is a fixed string, not a regular expression.

Solution 3:

First, you may try using sed:

npm info webpack | grep version: | sed 's/version: //'

or you may use awk:

npm info webpack | grep version: | awk '{print $2}'

which is probably easier.