1

I need some help with parsing a string in Linux.

I have a string:

[INFO] Total time: 2 minutes 8 seconds

and want to get only

2 minutes 8 seconds
3
  • 1
    Have you actually read man sed? Commented Nov 14, 2011 at 9:38
  • I try with grep but it is wrong Commented Nov 14, 2011 at 9:39
  • 1
    What makes you think that grep is the right tool for this job? Is this a case of "only have a hammer, everything looks like a nail"? Commented Nov 14, 2011 at 9:42

6 Answers 6

10

Using grep:

$ echo '[INFO] Total time: 2 minutes 8 seconds' | grep -o '[[:digit:]].*$'
2 minutes 8 seconds

Or sed:

$ echo '[INFO] Total time: 2 minutes 8 seconds' | sed 's/.*: //'
2 minutes 8 seconds

Or awk:

$ echo '[INFO] Total time: 2 minutes 8 seconds' | awk -F': ' '{print $2}'
2 minutes 8 seconds

Or cut:

$ echo '[INFO] Total time: 2 minutes 8 seconds' | cut -d: -f2
 2 minutes 8 seconds

And then read sed & awk, Second Edition.

Sign up to request clarification or add additional context in comments.

Comments

7

The sed and perl options do work, but in this trivial case, I'd prefer

 echo "[INFO] Total time: 2 minutes 8 seconds" | cut -d: -f2

If you have something against spaces, you can just use

 echo "[INFO] Total time: 2 minutes 8 seconds" | cut -d: -f2 | xargs

or even...

 echo "[INFO] Total time: 2 minutes 8 seconds" | cut -d: -f2 | cut -c2-

PS. Trivia: you could do this with grep only if grep implemented positive lookbehind like this egrep -o '(?<=: ).*'; Unfortunately neither POSIX extended regex nor GNU extended regex implement lookbehind (http://www.regular-expressions.info/refflavors.html)

Comments

5

If the line prefix is always the same, simply use sed and replace the prefix with an empty string:

sed 's/\[INFO\] Total Time: //'

Assuming that the time is always the last thing in a line after a colon, use the following regex (replace each line with everything after the colon):

sed 's/^.*: \(.*\)$/\1/'

Comments

1

If you prefer AWK then it is quite simple

echo "[INFO] Total time: 2 minutes 8 seconds" | awk -F": " '{ print $2 }'

Comments

0

Use sed or perl:

echo "[INFO] Total time: 2 minutes 8 seconds" | sed -e 's/^\[INFO\] Total time:\s*//'
echo "[INFO] Total time: 2 minutes 8 seconds" | perl -pe "s/^\[INFO\] Total time:\s*//;"

Comments

0

If you are getting the info from the terminal then you can grep out the info and use cut with the delimiter to remove everything before the info you want. grep INFO | cut -f2 -d:

If you want the info out of a file then you can grep the file grep INFO somefilename | cut -f2 -d:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.