Can anyone help me with this:

I am trying to extract a time stamp, by matching a string. For this am using combination of grep/awk commands. As the sting has 4 spces before [1] and one after, am confused how to work around it. Am new to programming, so need some help here.

IS="$(grep 'Starting    [1] TaskInit' process.log |  awk '{print $4}')"
echo "$IS"

Aim: It should match the string in the process.log file and should print out the time stamp related to that row.

  • 1
    If you surround the pattern with ', spaces should not be any problem. What’s your expected result and what are you getting instead? Have you tried to break your command down and debug its parts? – Melebius Jul 17 '19 at 7:26
  • I have surrounded it with ', when am trying to print the output its giving me nothing. If I keep only TaskInit as part of the string, its printing the time. But, there are many TaskInit's in the log file. That is why I want to extract the value from the above string. – Manoj Kumar Jul 17 '19 at 7:31

The spaces are not the problem here, it should work fine.
But the brackets [ need to be escaped in regex. So write:

grep 'Starting    \[1] TaskInit' process.log

In your case, as you want to match a fixed string and not a regex, you should use grep -F instead. Then you don't need to escape:

grep -F 'Starting    [1] TaskInit' process.log
|improve this answer|||||
  • The second format worked here for me. The first one is giving nothing in return. – Manoj Kumar Jul 17 '19 at 7:41
  • There is a typo in the first format: the closing bracket should also be quoted: \[1\] in place of \[1] – MoonCactus Nov 15 '19 at 8:24

You just need to escape the square brackets, because they have special meaning:

grep 'Starting    \[1\] TaskInit' process.log

In addition I would use only awk for this task, for this purpose you need something like:

awk '/Starting    \[1] TaskInit/ {print $4}' process.log
|improve this answer|||||
  • 1
    the closing bracket does not need to be escaped. – pLumo Jul 17 '19 at 7:36
  • 1
    +1 for awk only solution. – pLumo Jul 17 '19 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.