1
I have a multiline Bash variable: $WORDS
containing one word on each line.
I have another multiline Bash variable: $LIST
also containing one word on each line.
I want to purge $LIST
from any word present into $WORDS
.
I currently do that with a while read
and grep
but this is not sexy.
WORDS=$(echo -e 'cat\ntree\nearth\nred')
LIST=$(echo -e 'abcd\n1234\nred\nwater\npage\ncat')
while read -r LINE; do
LIST=$(echo "$LIST" | grep -v "$LINE")
done <<< "$WORDS"
echo "$LIST"
I think I can do it with awk
but did not managed to make it work.
Can someone explain me how to do it with awk?
Be careful with this as the grep will also match substrings. For example, if "cat" is in the $WORDS list, it will filter out not just cat, but also category, cattle, vacate, etc. If you can add ^ and $ to each word it should work. Try this:
echo "$LIST" | grep -vf <(echo "$WORDS" | sed -re 's/(.*)/^\1$/')
– virtex – 2017-06-09T13:14:25.1431Or
grep -x
, if that is a problem. – Michael Vehrs – 2017-06-09T13:27:40.367Very nice answer, thanks. The question was about awk, so I selected the corresponding answer, but I used your anwser. – Gregory MOUSSAT – 2017-06-10T00:37:01.080