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.
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
awk '{for(i=1;i<=NF;i++){if($i~/apple/){if(i==NF){printf("%s", $i);} else {printf("%s ",$i);}}}print "";}' <input.txt>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With