I have a sometextfile.txt with '|' as delimiter.

I would like to grep the value from last column only which consist of word "apple". How do i do it?


and grep whole row to a Newfile.txt


Another awk approach:

awk -F\| '$NF ~ /^apple$/' infile.txt >toOutput.txt
  • 1
    that works but in english, "consist of" means "equals", not "contains". – cas Aug 2 '17 at 5:56
  • any better enhancement? @cas – user6308605 Aug 2 '17 at 6:03
  • This will also accept pineapple or apples – Philippos Aug 2 '17 at 6:03
  • @user6308605 AFSHIN's answer is almost the same as mine except that it uses a ~ regexp match rather than a strict == equivalence match (so will, e.g. also match pineapple and apples, and anything else containing apple). You weren't 100% clear on this so that may or may not be what you actually want. ASHFIN's version also relies on the default/implicit action of awk (which is to print the current line), while mine has {print} explicitly in the script - that makes no real difference, I only included print in mine to make it clearer what the script is doing. – cas Aug 2 '17 at 6:16
awk -F'|' '$NF == "apple" {print}'  sometextfile.txt  > Newfile.txt

Using | as the field separator, for each line of sometextfile.txt if the last field ($NF) equals "apple", print the whole line. Redirect output to Newfile.txt

If you want to test for a specific column rather than the last column, use $n where n is the column number. In this example, $NF is equivalent to $7, and $6 would contain fffffff

  • I am sorry, there shouldn't be '|' at front. Updated my question – user6308605 Aug 2 '17 at 5:45

The original question asked for a grep solution. To find the last column, search for a word which does not have the delimiter [^|]+ forward to end-of-line $:

grep -Eo "[^|]+$" infile.txt



The straight solution is to anchor your expression at the end with a $:

grep "|apple$" sometextfile.txt > Newfile.txt

If this doesn't find the lines, the typical reason is a DOS-formatted text file with trailing carriage returns at the line endings. You can catch that case by allowing trailing non-printable characters at the end (supposing your regex support \s):

grep "|apple\s*$" sometextfile.txt > Newfile.txt
  • for some reason it does not work – user6308605 Aug 2 '17 at 5:54
  • The typical reason for this would be a DOS-formatted text file with a hidden carriage return at the end. Could that be? – Philippos Aug 2 '17 at 6:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.