Reputation: 55
Im trying to search through a file that only contains sequences of four words per line ie. the file looks like
walked the dog fast
jumped the moon high
on my nothing sun
on my not grass
and my code looks like
LINE=$(grep "^$PREV_THREE $PREV_TWO $PREV_ONE" $INPUT_FILE)
NEXT_WORD="${LINE##* }"
I use $PREV_THREE $PREV_TWO $PREV_ONE
as the three words to indicate which fourth word to get from a specific line. My issue is that when $PREV_THREE $PREV_TWO $PREV_ONE
equals on my not
it sets NEXT_WORD
equal to sun
instead of grass
. Is there an elegant way to Grep the first three words to find a perfect match and then set next to the fourth word? Instead of what I have above which just finds an occurrence of my pattern.
Upvotes: 0
Views: 962
Reputation: 785156
It is easier to use a single awk
command for this:
awk -v p='$PREV_THREE $PREV_TWO $PREV_ONE ' '$0 ~ p {print $4}' "$INPUT_FILE"
grass
btw your grep
can also have a trailing space after last search word to make sure you don't match partial word. Consider this gnu grep
:
grep -oP "^$PREV_THREE $PREV_TWO $PREV_ONE \K.+" $INPUT_FILE
grass
Upvotes: 2