Given a file, for example:
potato: 1234
apple: 5678
potato: 5432
grape: 4567
banana: 5432
sushi: 56789
I'd like to grep for all lines that start with potato:
but only pipe the numbers that follow potato:
. So in the above example, the output would be:
1234
5432
How can I do that?
One can think of Grep as a restricted Sed, or of Sed as a generalized Grep. In this case, Sed is one good, lightweight tool that does what you want -- though, of course, there exist several other reasonable ways to do it, too.
You can use grep, as the other answers state. But you don't need grep, awk, sed, perl, cut, or any external tool. You can do it with pure bash.
Try this (semicolons are there to allow you to put it all on one line):
## tells bash to delete the longest match of ": " in $line from the front.
or if you wanted the key rather than the value, %% tells bash to delete the longest match of ": " in $line from the end.
The substring to split on is ":\ " because the space character must be escaped with the backslash.
You can find more like these at the linux documentation project.
This will print everything after each match, on that same line only:
This will do the same, except it will also print all subsequent lines:
These command-line options are used:
-n
loop around each line of the input file-l
removes newlines before processing, and adds them back in afterwards-e
execute the perl codeOr use regex assertions:
grep -oP '(?<=potato: ).*' file.txt
or
or
or
or
or