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.

Share:
7,068

Related videos on Youtube

RIchard Williams
Author by

RIchard Williams

Updated on September 18, 2022

Comments

  • RIchard Williams
    RIchard Williams over 1 year

    I have a file (file_name) which contains exactly one occurance of the string Result:, at the start of a line. I want to print all the characters after the string Result: 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
    user unknown over 12 years
    There is a blank behind the colon : and afaik, the word before the next colon is searched.
  • Tim Kennedy
    Tim Kennedy over 12 years
    the 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
    user unknown over 12 years
    Sorry - I meant 'before the next blank'. Your command results for the line Result:two bla nk in bla.
  • Tim Kennedy
    Tim Kennedy over 12 years
    I 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
    Arcege over 12 years
    The OP stated that "Result: " has only one occurrence in the file. It could be anchored with ^, but is unnecessary.
  • Arcege
    Arcege over 12 years
    The OP asks to get only the word after "Result: ", not the entire line.
  • user unknown
    user unknown over 12 years
    Yes - 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
    Arcege over 12 years
    If the line is Result: 2 apples, then your's would get 2 apples, not 2 as the OP suggested.
  • user unknown
    user unknown over 12 years
    No. egrep -o only grabs Result: 2 - the second line removes the Result:. Did you test it? You should!