Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

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

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

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

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

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.

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.