Monday, November 28, 2011

linux shell process filename from a text file

In my TA work I need to do the following:

Given a text file called names.txt, which contains all student ids:
aaa
bbb
ccc
ddd

Now I need to grep all files with a prefix matching one of the ids in names.txt, that is, I need to get

aaa.cpp
bbb.cpp
ccc.cpp

but the directory might contain a lot more other *.cpp

The first blessing is from grep

ls *.cpp | grep -f names.cpp > filenames.txt
gives the filenames that matching any entry in names.cpp

Now comes the hard part, how do you use those entries.

ls or find comes into mind but I don't know how to use them with input filename from a text file.

So it is awk.

awk '{ cmd="ls -l " $0; system(cmd) }' < filenames.txt

And that's it.

No comments:

Post a Comment