How to use 'sed' with piping

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.


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.


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.

Tags:

Bash

Grep

Sed