I am currently dealing with a folder containing about 1000 files and I have to extract some filenames from this folder and create another file (configuration file) containing these filenames.

Basically, the folder has filenames in the following format :


and so on up until


I just want to extract out all files which have "Apple_A" in them. Also, I want to create another file which has 'labels' (Unix variables) for each of these "Apple_A" files whose values are the names of the files. Also, the 'labels' are part of the filenames (everything up until the word "Apple") For example,


and so on...till


Could you tell me a one-line Unix command that does this ? Maybe using "awk" and "sed"


I'd do this in two steps.

Create a file called all_apple_a.dat listing all files with "Apple_A" in the filename:

ls | grep Apple_A > all_apple_a.dat

Create a file called labelled_apples.dat which 'labels' your filenames:

perl -pe 's/(\d+_Apple)(.*)/\1=\1\2/' all_apple_a.dat > labelled_apples.dat
  • It's much better to use ls *Apple_A* instead of ls | grep Apple_A. – rush Sep 26 '12 at 12:51
  • @rush - Oh? Why is that? – ire_and_curses Sep 26 '12 at 17:00
  • here is the answer: mywiki.wooledge.org/ParsingLs – rush Sep 26 '12 at 20:21
  • @rush - Thanks for the globbing notation. It's a good point, and you're right that it is better. I'm aware of that (good) article, and I agree. But I'll note that unless you're putting newlines in your filenames (in which case you have other problems), there isn't really any issue with grepping here, especially for simple command line tasks that are not scripts. – ire_and_curses Sep 26 '12 at 21:23
  • anyway one command is always better than two (: – rush Sep 27 '12 at 6:44

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.