3

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.

7

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.

  • There is a blank behind the colon : and afaik, the word before the next colon is searched. – user unknown Nov 7 '11 at 4:39
  • 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. – Tim Kennedy Nov 7 '11 at 5:10
  • Sorry - I meant 'before the next blank'. Your command results for the line Result:two bla nk in bla. – user unknown Nov 7 '11 at 5:29
  • 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. – Tim Kennedy Nov 7 '11 at 5:40
3

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.

  • 2
    The OP stated that "Result: " has only one occurrence in the file. It could be anchored with ^, but is unnecessary. – Arcege Nov 7 '11 at 6:29
0
tillblank=$(egrep -o "^Result: [^ ]* " file)
echo ${tillblank/*:/}

egrep -o only outputs the pattern you searched for. The next line removes everything up to the colon.

  • The OP asks to get only the word after "Result: ", not the entire line. – Arcege Nov 7 '11 at 6:30
  • 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? – user unknown Nov 7 '11 at 18:23
  • If the line is Result: 2 apples, then your's would get 2 apples, not 2 as the OP suggested. – Arcege Nov 8 '11 at 0:46
  • No. egrep -o only grabs Result: 2 - the second line removes the Result:. Did you test it? You should! – user unknown Nov 8 '11 at 1:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.