Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Moving Files based on Content

Status
Not open for further replies.

bligh68

IS-IT--Management
Sep 17, 2009
2
CA
I have a directory of files, each file has a header that contains either cat=a, cat=b, or cat=c

I need to move each file to a different directory that corresponds with it's category.

I've been playing with this for the last while, and it's easy enough to sort out the files I want. head -n 1 * | awk '/cat=A/' But I can't seem to make the leap that lets me move the files from this output to a different directory.

Thanks
 
I have non awk solution.
Let say you have file_a file_b file_c
file_a looks like this
Code:
cat=a
text in file a
file_b looks like this
Code:
cat=b
text in file b
file_c looks like this
Code:
cat=c
text in file c
and you want to move the file containing cat=a into directory called dir_a.
This should do the job.

Code:
grep -lr "cat=a" file*|xargs -I {} -t  mv  {}  dir_a/
 
Here is incomplete awk solution
Code:
awk 'NR==1 && /"cat=a"/{} END{print system("cp " ARGV[2] " dir_a/") }' file*
In that case will move file_b
Just need a way to get the right filenames that are matching the cat=a regex and call them instead the ARGV[2] at the END{...}
 
Code:
awk -F= 'FNR==1 { print "mv",FILENAME,"dir_"$2"/" }' file* | sh

Annihilannic.
 
Brilliant! Both ideas work a treat! Thanks so much.
 
Thank you. I was not aware of the FILENAME variable.
Need to do some more awk RTFM.
Just for completeness of my initial try.

Code:
awk  '/cat=b/{system("cp " FILENAME " dir_b/") }' file*
Which is still inefficient.

Based on Annihilannic solution, but using system(...) instead
Code:
awk -F=  'FNR==1{system("cp " FILENAME " dir_"$2)}' file*
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top