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 justgrep
:Explanation:
From
man grep
:The lookbehind
(?<=Path=)
asserts that at the current position in the string, what precedes is the charactersPath=
. 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.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 issed
and it can produce the same results, but by substituting the PATH= part of the line with""
, i.e.The
-n
overridessed
s default behavior of 'print all lines' (so-n
= no print), and to print a line, we add thep
character after the substition. Only lines where the substitution happens will be printed.This gives you the behavior you have asked for, of
grep
ing for a string, but removing thePath=
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 isIHTH
grep
greps a line of text and displays it.head
displays the first n lines of text, not characters.You're looking for
sed
orawk
:This sets
=
as a field separator and prints the second field.With GNU grep:
\K
keeps the stuff left of the \K, don't include it in$&
.Of course the solution is to use
grep -Po
.Let's add some other solutions, for completeness:
with
cut
, setting the delimiter the=
:It might be a bit risky, but you can also source the file, so that
$Path
will contain the value.Test
As per comments, see how to
source
just part of the file: