You are not logged in.
I have a program that outputs data to the console in this format:
[1] banana
[2] orange
[7] apple
[17] grape
[42] strawberry
I would like to strip this output and only get the values for [2] and [17]. So my output would be:
orange
grape
My first idea was to pipe the output to grep and then possibly use sed to strip the preceding numbers and brackets. What is the recommended way to do this and why? Is there a better suited utility that I'm not aware of?
Last edited by nadman10 (2013-11-06 16:48:54)
Offline
Grep whatever values you want and remove the brackest with the numbers with e.g.
sed 's/\[.*\] //' <filename>
Last edited by karol (2013-11-06 16:21:00)
Offline
Grep whatever values you want and remove the brackest with the numbers with e.g.
sed 's/\[.*\] //' <filename>
Thank you Karol. You always seem to have the correct answers. Is this the most efficient way of doing this? I can't think of more simple way of doing it other than this.
Offline
You can use 'cut'
grep -e "\[2\]" -e "\[17\]" <filename> | cut -d ' ' -f 2
Offline
grep + (cut/sed) = awk.
awk '/\[(2|17)\]/ { print $2; }'
The first equation is the logical one, but the value version would be the inequality:
awk > grep + (cut|sed)
Last edited by Trilby (2013-11-06 16:39:58)
"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman
Offline
grep + (cut/sed) = awk.
Very true.
awk '/\[(2|17)\]/ { print $2; }'
I wanted OP to google / RTFM this himself
The idea to use sed was correct, nadman10. You should have googled
remove "square brackets" sed
and you would have found out the answer yourself: http://www.unix.com/showthread.php?t=159143
The slightly tricky part with the square brackets is that they have special meaning, so you have to escape them i.e. precede them with '\'.
Offline
You can use 'cut'
grep -e "\[2\]" -e "\[17\]" <filename> | cut -d ' ' -f 2
Your grep syntax is much more simple than mine. I'm going to use this in conjunction with what you suggested with sed. Thanks for your help guys!
Offline
I wanted OP to google / RTFM this himself
Touche.
To justify my seeming inconsistency (with other thread(s)), I think providing working awk commands reveals what can be done which highlights what there is to learn about. One would likely still need to read up on the tool to understand how/why it is done and how else it could be applied.
"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman
Offline
karol wrote:You can use 'cut'
grep -e "\[2\]" -e "\[17\]" <filename> | cut -d ' ' -f 2
Your grep syntax is much more simple than mine.
This wasn't meant to be simple, but readable.
You can compress
grep -e "\[2\]" -e "\[17\]"
to
grep -E '\[(2|17)\]'
but I think stepwise refinement is a better approach, so I started with something that's IMHO easier to figure out.
Last edited by karol (2013-11-06 16:54:34)
Offline
It wasn't that I didn't RTFM, I was looking for the most efficient way to it.
Offline