Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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


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.