Returning only the portion of a line after a matching pattern
7,068
Solution 1
The simplest way would be to use awk
.
awk '/^Result: / {print $2}' file_name
That matches lines that begin with Result:
, and prints the second field in the file, as defined by the default $IFS, which is whitespace.
Solution 2
Sounds like what you want is:
sed -ne 's/^Result: \([^ ]*\).*/\1/p' file_name
Matches against the line with "Result: " and prints the first word after it. Other lines are not displayed.
Related videos on Youtube
Author by
RIchard Williams
Updated on September 18, 2022Comments
-
RIchard Williams over 1 year
I have a file (
file_name
) which contains exactly one occurance of the stringResult:
, at the start of a line. I want to print all the characters after the stringResult:
in that line until I encounter a space. Which shell command should I use?grep "Result: " file_name | tail -c +9
is not working.
-
user unknown over 12 yearsThere is a blank behind the colon
:
and afaik, the word before the next colon is searched. -
Tim Kennedy over 12 yearsthe OP doesn't mention a second colon. Just that the string ocurring between
Result:
and the next space are what is desired. Awk will by default break up the line on white space.$1
= "Result:", $2 = the next word. Which is what the OP requested to extract. -
user unknown over 12 yearsSorry - I meant 'before the next
blank
'. Your command results for the lineResult:two bla nk
inbla
. -
Tim Kennedy over 12 yearsI have updated my example to specifically include the space after the colon following
Result:
. This will now ignore lines like that in your example, and more closely match the initial request of the OP. -
Arcege over 12 yearsThe OP stated that "Result: " has only one occurrence in the file. It could be anchored with
^
, but is unnecessary. -
Arcege over 12 yearsThe OP asks to get only the word after "Result: ", not the entire line.
-
user unknown over 12 yearsYes - the first line one grabs the matching pattern, and the second line removes the "Result: " from the beginning. Doesn't it work for you? What do you get?
-
Arcege over 12 yearsIf the line is
Result: 2 apples
, then your's would get2 apples
, not2
as the OP suggested. -
user unknown over 12 yearsNo. egrep -o only grabs
Result: 2
- the second line removes theResult:
. Did you test it? You should!