Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an output file which contains different numbers seperated by commas. But 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 untill the last number.

share|improve this question
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 '13 at 17:51


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.

share|improve this answer
Huh? The grep could be only grep -oE '[^,]+' TMPFILE. – manatwork Mar 6 '13 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 '13 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



share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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