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 am just a beginner with Unix and so my skills in Unix commands is limited. 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 :

1_Apple_A_someword.txt 
1_Apple_B_someword.txt 
2_Apple_A_someword.txt 
2_Apple_B_someword.txt 
3_Apple_A_someword.txt 
3_Apple_B_someword.txt

and so on up until

1000_Apple_A_someword.txt
1000_Apple_B_someword.txt

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,

1_Apple=1_Apple_A_someword.txt
2_Apple=2_Apple_A_someword.txt
3_Apple=3_Apple_A_someword.txt

and so on...till

1000_Apple=1000_Apple_A_someword.txt

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

Thanks.

share|improve this question
    
Same question on SO –  Thor Sep 26 '12 at 7:33
add comment

1 Answer 1

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
share|improve this answer
    
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
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.