I have ~2k files that I want to extract 12 of 26 columns and save the extracted information into a new file. I have been doing this for individual files using

cat "oldfile.csv" | grep -v "=" | cut -f 1-4,9,14,15,19,21,22,24,26 > newfile.csv

There must be a way to do all files with one Unix series of commands.

Any help is greatly appreciated


The shell can do loops:

for i in *.csv; do 
    grep -v "=" "$i" | cut -f 1-4,9,14,15,19,21,22,24,26 > "new.$i"

Although, if you have embedded field separators in your fields, this will bomb. But not because of the loop.

| improve this answer | |
  • 1
    $i needs quoting, or it will break on filenames containing characters in IFS. – Chris Down Jan 30 '12 at 17:07
  • Spot on. I stand corrected. – Alien Life Form Jan 30 '12 at 17:13

If you want to provide particular files as argument to a script e.g. script named process_csv.sh

for arg; do
    grep -v "=" "${arg}" | cut -f 1-4,9,14,15,19,21,22,24,26 > "${arg}.new"

Now you can run this script as following,

./process_csv.sh *.csv OR

./process_csv.sh first.csv fifth.csv seventh.csv OR

./process_csv.sh somefile1 somefile2

Before somebody points it out, in the above script, if you do not want to preserve the arguments you can use shift in the script.

| improve this answer | |

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.