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?


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

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.