I have a file with words separated by ',' on lines, every line has the same number of words, say 4. So ther are in the form of:

something1,something2,something3,something4

I want to search for the line that contains on the 4th column exactly something4, but how do i do that if there exists another line that is something like this:

something1,something2,something3,1_something4

with grep I will get both these lines, but I only want the line that has on the 4th element exactly something4 what should I do?

marked as duplicate by thrig, Jeff Schaller, elbarna, JigglyNaga, schily Nov 22 at 17:02

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 10 down vote accepted

You can use awk for this:

awk -F, '$4 == "something4"' file.csv

This should print the entire line for any line where the 4th column is exactly something4


In order to pass a variable into awk you would need to do the following:

var1=$(echo "something,something4" | cut -f2 -d,)
awk -F, -vsearch="$var1" '$4 == search' file.csv
  • Why doesn't this work if I do if with a variable? – C. Cristi Nov 21 at 20:21
  • Say I have var1=$(echo "something,something4" | cut -f2 -d,) and I try to awk -F, '$4 == "$var1"' file.csv but if I go and ``` echo "$var1"``` I get the good result, and there exits something4 in file.csv – C. Cristi Nov 21 at 20:22
  • @C.Cristi: I have updated my answer. Let me know if it doesn't work for you. – Jesse_b Nov 21 at 20:24
  • It works, but why? – C. Cristi Nov 21 at 20:26
  • 1
    Your shell variable won't expand inside the single quotes around the awk command. So awk has the -v option to pass variables into the awk program. – Jesse_b Nov 21 at 20:28

Or, since there's only 4 columns and you want something specific in the last one,

grep ',something4$' < input

(posted in case you're actually OK with grep; awk is a great solution here).

Generally, for this type of problem you can use cut to get only the column you want, then grep on that.

echo something1,something2,something3,something4 | cut -d , -f 4 | grep '^something4$'

  • 1
    The only problem with this is the assumption that the OP wants to find the line that matches. – Jeff Schaller Nov 23 at 12:00
  • You're right. cut would only be useful for checking for match/no match or counting matches. Or finding all column values that match a regexp. – Lassi Nov 23 at 15:17

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