1

I am trying to print out a specific string within a line with sed.

The first problem is that I have some difficulties finding a string which contains slashes, I already tried some solutions provided in other threads but was unsuccessful, hopefully someone can help me.

I have a file called output.log.

An example of a line is:

013-11-08 19:45:52 evtlog.bad PROD/INSE/6004113 2012-11-08 19:04:06 /test11/golf/TierTwo/2013-11/evtlog.log

So with sed I want to print out only below string from this line:

/test11/golf/TierTwo/2013-11/evtlog.log

And I want to find the string in this line with: "golf/TierTwo/2013-11"

So I would use for example:

sed 'golf/TierTwo/2013-11' output.log

And get an output of:

/test11/golf/TierTwo/2013-11/evtlog.log

How can I achieve this?

If there would be a better solution instead of sed, it would be welcome also. My goal is to use this in a script, either bash or perl

2
  • 1
    Could specify if it has to be solved with sed or if you just want to solve the problem? Because every problem that can be solved with sed can and will also be solved with awk or perl. If you don't care it is better to rewrite your question so it is more general. Commented Sep 20, 2016 at 8:29
  • Hi, the problem can be solved with any solution, will edit my question. thanks
    – Flemx
    Commented Sep 20, 2016 at 9:18

3 Answers 3

1

Use awk instead of sed:

awk 'index($0,"golf/TierTwo/2013-11")>0 { print $7 }' output.log

this will search the string in each line, if an index is found 7th word will be printed.

3
  • Hi, it seems this command prints out the 7th word of every line in the document.
    – Flemx
    Commented Sep 20, 2016 at 8:39
  • but not specific the line that contains the string.
    – Flemx
    Commented Sep 20, 2016 at 9:17
  • 1
    @Flemx, yes because "golf/TierTwo/2013-11" being a string and non-empty, it means true. Here, you want to use the regexp matching operator, so /.../ (though you'd need to escape the / within) or $0 ~ "..." Commented Sep 20, 2016 at 10:05
0

If your grep supports the -o or --only-matching flag, you could grep for the string, surrounded by any contiguous non-whitespace characters

grep -o '[^[:blank:]]*golf/TierTwo/2013-11[^[:blank:]]*' output.log
/test11/golf/TierTwo/2013-11/evtlog.log

or (if it supports the perl-style \S class)

grep -Eo '\S*golf/TierTwo/2013-11\S*' output.log
/test11/golf/TierTwo/2013-11/evtlog.log
0
0
perl -naE 'say $F[6] if m!golf/TierTwo/2013-11!' logfile

perl -nae makes perl behave in a awk way...

You must log in to answer this question.

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