I have an output file which contains different numbers separated by commas. The issue is I do not know the number of commas.

I would in turn like this data to be grep on another file. For example:

I have INFO: 10,20,30,55,58,47,52,100

I use

awk '{split($0,a,","); for (i=1; i<=8; i++) print a[i]}' TMPFILE

to extract the data. But I do not know how long the for loop has to be performed.

Once I get those numbers like 10, I need to grep that on data.txt then 20 on data.txt and so on until the last number.

  • 1
    For future reference, this kind of data is called "CSV" data (for "Comma Separated Value"). Might be useful to know that if you are doing internet searches related to processing it, since CSV processing is a common task.
    – goldilocks
    Mar 6, 2013 at 17:51

2 Answers 2



echo '10,20,30,55,58,47,52,100' | \
awk '{x=split($0,a,","); for (i=1; i <= x; ++i) print a[i]}'

awk using field separator:

echo '10,20,30,55,58,47,52,100' | \
awk -F ',' '{for(i=1; i <= NF; ++i) print $i}'


 echo '10,20,30,55,58,47,52,100' | sed 's/,/\n/g'

So, then the command would be e.g.:

sed 's/,/\n/g' TMPFILE | xargs -I'{}' grep '{}' data.txt

Or, as using xargs perhaps:

xargs -a TMPFILE -d, -I'\x' grep '\x\{1\}' data.txt

Or, if you do not want to use xargs perhaps; making pattern file with sed:

sed 's/\([^,]\+\),*/^\1$\n/g' TMPFILE | \
grep -o -f /proc/self/fd/0 data.txt


tr ',' '\n' < TMPFILE | \
grep -f /proc/self/fd/0 data.txt

All depending on what and how you want to grep.

  • 1
    Huh? The grep could be only grep -oE '[^,]+' TMPFILE.
    – manatwork
    Mar 6, 2013 at 17:48
  • @manatwork: Yes, but not for fulfilling last requirement: "Once I get those numbers like 10, I need to grep that on data.txt then 20 on data.txt and so on untill the last number."
    – Runium
    Mar 6, 2013 at 18:13

If want to repeatedly grep the same file, you could also try a shell loop:

for i in $(cat csvfile)
  grep "$i" datafile
done > outfile

If you do not put it in a script or a subshell you need to


before and



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.