camilo soto
camilo soto

Reputation: 1271

save the output of a bash file

i have some files in a folder, and i need the first line of each folder

transaction1.csv
transaction2.csv
transaction3.csv
transaction4.csv

and i have the next code

#All folders that begin with the word transaction

folder='"transaction*"'

ls `echo $folder |sed s/"\""/\/g` >testFiles

# The number of lines of testFiles that is the number of transaction files

num=`cat testFiles | wc -l`

for i in `seq 1 $num`
do
    #The first transaction file
    b=`cat testFiles | head -1`

    #The first line of the first transaction file
    cat `echo $b` | sed -n 1p 

    #remove the first line of the testFiles
    sed -i '1d' testFiles 
done

This code works, the problem is that i need save the first line of each file in a file

and if i change the line:

cat `echo $b` | sed -n 1p > salida

it not works =(

Upvotes: 1

Views: 705

Answers (4)

Adam H. Peterson
Adam H. Peterson

Reputation: 4591

head -qn1 *.csv

head -n1 will print the first line of each file, and -q will suppress the header when more than one file is given on the command-line.

=== Edit ===

If the files are not raw text (for example, if they're compressed with "bzip2" as mentinoned in your comment) and you need to do some nontrivial preprocessing on each file, you're probably best off going with a for loop. For example:

for f in *.csv.bz2 ; do
    bzcat "$f" | head -n1
done > salida

(Another option would be to bunzip2 the files and then head them in two steps, such as bunzip2 *.csv.bz2 && head -qn1 *.csv > salida; however, this will of course change the files in place by decompressing them, which is probably undesirable.)

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77105

In bash:

for file in *.csv; do head -1 "$file" >> salida; done

As Adam mentioned in the comment this has an overhead of opening the file each time through the loop. If you need better performance and reliability use the following:

for file in *.csv; do head -1 "$file" ; done > salida

Upvotes: 3

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Using sed:

for f in *.csv; do sed -n "1p" "$f"; done >salida

Upvotes: 0

Kent
Kent

Reputation: 195059

this awk one-liner should do what you want:

awk 'FNR==1{print > "output"}' *.csv

the first line of each csv will be saved into file: output

Upvotes: 1

Related Questions