1

Im trying to get a certain part of my output from grep. Currently I get the full text that could look like: "Location: /path/to/file" or "State: Error". However I want to only print the second part that is "/path/to/file" and "Error". Observe that one output contains "Elapsed time: 568 hours (23.6 days)" and I need to remove the hours (23.6 days) part. These are all different grep and unique code can be used for each one.

So what I expect as a result is to give the input:

Elapsed time:    568 hours (23.6 days)

and the output should be 568

For the other example I expect as a result is to give the input:

State:    Error

And the output should be Error

I tried to check up something called awk and sed, got a little confused and not very clear how to implement it on my problem.

`grep "Elapsed Time: *" | sed -e 's/Elapsed Time://g'` 

this would print out 568 hours (23.6 days).

 grep "Location: *" | sed -e 's/Location://g' 

works but contains a lot of empty space between Location: and /path/to/file, can the spaces be removed in one go aswell?

Fredrik
  • 477
  • 4
  • 22
  • @Cyrus Thank you, added some text on what the exact input is and what output I want to achieve, about links I dont really have any good references – Fredrik Sep 08 '19 at 18:04
  • Possible duplicate of [How to grep for contents after pattern?](https://stackoverflow.com/questions/10358547/how-to-grep-for-contents-after-pattern) – tripleee Sep 10 '19 at 06:48

1 Answers1

3

If row contains Elapsed time: print third column:

echo 'Elapsed time:    568 hours (23.6 days)' | awk '/Elapsed time:/{print $3}'

or with GNU grep and Perl-compatible regular expression (PCRE)

echo 'Elapsed time:    568 hours (23.6 days)' | grep -Po 'Elapsed time: *\K.*(?= hours)'

or with GNU sed and extended regex:

echo 'Elapsed time:    568 hours (23.6 days)' | sed -r 's/Elapsed time: *(.*) hours.*/\1/'

Output:

568
Inian
  • 80,270
  • 14
  • 142
  • 161
Cyrus
  • 84,225
  • 14
  • 89
  • 153