Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have a bunch of CSV files in a directory like:

modfinalak_1.csv modfinalal_1.csv modfinalal_2.csv modfinalal_3.csv modfinalar_1.csv modfinalar_2.csv

so it's one or multiple files per each US state (AK, AL, AR, etc.). How can I use cat to combine all the files for each state and then rename the file to the state name?

In the above example, I want modfinal_1.csv,modfinalal_2.csv,and modfinalal_3.csv to be combined and renamed to al.csv. How do you get cat to do this based on the text before the '_' character?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Something like this would do it in bash (list all the state abbreviations in the list between in and ;):

 for s in ak al ar ; do cat *${s}_*.csv > $s.csv ; done

If you have the state abbreviations in a file states.txt, the line could look like this:

 for s in `cat states.txt` ; do cat *${s}_*.csv > $s.csv ; done
share|improve this answer

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.