88

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?

0

3 Answers 3

79

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.

2
  • 3
    The -E option obviously means to use ERE syntax, but my GNU sed 4.2.2 manual only mentions -r. -E works, though!
    – Law29
    Aug 2, 2016 at 8:11
  • 3
    @Law29 Yes. For all reasonably modern GNU sed, however, -E is an undocumented synonym for -r. The rumor is that POSIX has settled on -E, which BSD/OSX already uses, and, if that is added to the final standard, we will all be transitioning to -E.
    – John1024
    Aug 2, 2016 at 8:13
19

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.

7

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.

You must log in to answer this question.

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