How to command grep not to display the searched string? [duplicate]

I want to print a part of a line in a file. The whole line looks like this.

Path=fy2tbaj8.default-1404984419419

I want to print only the characters after Path=. I have tried grep Path filename | head -5. But its not working.It still shows the entire line. How can i do this?


You can use grep and just grep:

grep -oP "(?<=Path=).*" file

enter image description here

Explanation:

From man grep:

   -o, --only-matching
          Print only the matched (non-empty) parts of a matching line,
          with each such part on a separate output line.
   -P, --perl-regexp
          Interpret PATTERN as a Perl compatible regular expression (PCRE)

The lookbehind (?<=Path=) asserts that at the current position in the string, what precedes is the characters Path=. If the assertion succeeds, the engine matches the resolution pattern.

For Perl 5 regular expression syntax, read the Perl regular expressions man page.


you can use cut command for this purpose.

grep Path filename |cut -c6-

Here -c6- option means print from 6th to last character.


The awk solution is what I would use, but a slightly smaller process to launch is sed and it can produce the same results, but by substituting the PATH= part of the line with "" , i.e.

  sed -n 's/^Path=//p' file

The -n overrides seds default behavior of 'print all lines' (so -n = no print), and to print a line, we add the p character after the substition. Only lines where the substitution happens will be printed.

This gives you the behavior you have asked for, of greping for a string, but removing the Path= part of the line.

If, per David Foerster's comments, you have a large file and wish to stop processing as soon as you have matched and printed the first match to 'Path=', you can tell sed to quit, with the q command. Note that you need to make it a command-group by surrounding both in { ..} and separating each command with a ;. So the enhanced command is

sed -n 's/^Path=//{p;q;}` file

IHTH


grep greps a line of text and displays it. head displays the first n lines of text, not characters.

You're looking for sed or awk:

awk '{print $2}' FS='='

This sets = as a field separator and prints the second field.