Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
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 '13 at 17:51
add comment

2 Answers 2

akw:

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}'

sed:

 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

Or,

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
1  
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." –  Sukminder Mar 6 '13 at 18:13
add comment

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

IFS=,
for i in $(cat csvfile)
do
  grep "$i" datafile
done > outfile

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

oldIFS=$IFS

before and

IFS=$oldIFS

afterwards..

share|improve this answer
add comment

Your Answer

 
discard

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.