Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print every string that is matched by regex in order

Tags:

grep

bash

awk

After an hour of searching on the Internet, I still cannot make this simple task work properly:

Filter the following lines

strawberries blueberries tastyapplepies are on the desk
apple banana pineapple guava applejuice quite delicious

into

tastyapplepies
apple pineapple applejuice

by finding whether each field contains apple and using commands such as grep and awk.

like image 231
Kevin Dong Avatar asked Jan 28 '26 20:01

Kevin Dong


2 Answers

You need this:

awk '{c=0; for(i=1;i<=NF;i++) if($i~/apple/) printf "%s%s",(++c>1?OFS:""),$i; if (c) print ""}' file

Try all solutions for input where apple appears in the last field of some but not all lines, and a line that doesn't contain apple, e.g.:

$ cat file
strawberries blueberries tastyapplepies are on the desk
apple banana pineapple guava applejuice quite delicious
here is a line without the target word
here is a line ending in apple

$ awk '{c=0; for(i=1;i<=NF;i++) if($i~/apple/) printf "%s%s",(++c>1?OFS:""),$i; if (c) print ""}' file
tastyapplepies
apple pineapple applejuice
apple
like image 75
Ed Morton Avatar answered Jan 30 '26 13:01

Ed Morton


awk '{for(i=1;i<=NF;i++){if($i~/apple/){if(i==NF){printf("%s", $i);} else {printf("%s ",$i);}}}print "";}' <input.txt>
like image 23
Vikas Madhusudana Avatar answered Jan 30 '26 12:01

Vikas Madhusudana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!