1

I have the following line in a text file:

severity: Error , count: 10 violations , waived: 7, not waived: 3

How can extract the number after not waived: (i.e. 3) using a single grep command in a tcsh shell?

1
  • grep is the command to print the lines that match a pattern. That's what grep (g/re/p) stands for. Only some grep implementations (like pcregrep or GNU grep) have provision to print parts of the matching lines as an extension. What system are you on? More generally, what you're asking for is more a job for awk or sed. Feb 9, 2017 at 9:59

1 Answer 1

3

It would be easier with awk in this case:

% awk '{ print $NF }' file.txt
3

$NF is the data in the last whitespace-delimited field (column) in the input record (line).

grep is generally used to get whole lines matching a particular pattern, but some implementations may be used to get bits of lines as well, using the -o flag (will return only the bits that are matched):

% grep -o '[[:digit:]]$' file.txt
3

But for general processing of data on lines, I'd recommend awk over grep.

If the file contains other lines of less relevant data:

% awk '/^severity:/ { print $NF }' file.txt

If, additionally, the field is not at the extreme end of the line, you may want to use sed:

% sed -n '/^severity:/s/^.*not waived: \([[:digit:]]*\).*$/\1/p' file.txt
3
5
  • this is working for me now grep "severity" ace_sc.log | awk '{print $NF}' but what if in some other case something else is coming after not waived: 3 Feb 9, 2017 at 10:03
  • @vishnuvarkala To combine the two into one awk: awk '/severity/ { print $NF }' file.txt.
    – Kusalananda
    Feb 9, 2017 at 10:04
  • how can I capture the number coming after "not waived:" instead of getting the last whitespace-delimited field. something similar to this in perl not\swaived\:\s(\d+) Feb 9, 2017 at 10:10
  • @vishnuvarkala Updated my answer again.
    – Kusalananda
    Feb 9, 2017 at 10:16
  • 1
    @vishnu, if you know perl, why not use it: perl -lne 'print $1 if /\bnot waived:\s*(\d+)/' < file Feb 9, 2017 at 10:23

You must log in to answer this question.

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