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?
greplooks for any line that contains the stringpotato:, then, for each of these lines,sedreplaces (s///– substitute) any character (.*) from the beginning of the line (^) until the last occurrence of the sequence:(colon followed by space) with the empty string (s/...//– substitute the first part with the second part, which is empty).or
For each line that contains
potato:,cutwill split the line into multiple fields delimited by space (-d\–d= delimiter,\= escaped space character, something like-d" "would have also worked) and print the second field of each such line (-f2).or
For each line that contains
potato:,awkwill print the second field (print $2) which is delimited by default by spaces.or
All lines that contain
potato:are sent to an inline (-e) Perl script that takes all lines fromstdin, then, for each of these lines, does the same substitution as in the first example above, then prints it.or
The file is sent via
stdin(< file.txtsends the contents of the file viastdinto the command on the left) to anawkscript that, for each line that containspotato:(if(/potato:/)returns true if the regular expression/potato:/matches the current line), prints the second field, as described above.or
The file is sent via
stdin(< file.txt, see above) to a Perl script that works similarly to the one above, but this time it also makes sure each line contains the stringpotato:(/potato:/is a regular expression that matches if the current line containspotato:, and, if it does (&&), then proceeds to apply the regular expression described above and prints the result).