1

I have a bunch of csv 's in folder.I want to combine them in an order.

I have the csv files as

state_1_result_6.csv,
state_1_result_8.csv,
state_1_result_10.csv,
state_1_result_12.csv.....

Each of the csv has one line without no header, so the content of a state_i_result.csv will be like:

1,2,3,69,19,1,2,6,10,12,30,28

I want to combine in such a order that first line will be state_1_result_6.csv and second line will be state_1_result_8.csv and so on.

I tried with

cat state*.csv > final.csv

But it is not merging in a order.

  • is there any pattern on the is from state_i_result.csv? Every 2 starting from 6? So we can build a loop to generate them. – fedorqui Jan 4 '17 at 8:55
  • I edited the question now.The i are same in state_i_result_j.csv.The j has a pattern 6,8,10,12 only. – John Jan 4 '17 at 9:24
1

Since you know them, just loop through the list of indexes:

for i in 6 8 10 12;
do
   cat state_1_result_${i}.csv >> final.csv
done

You can also use a C-loop:

for ((i=6; i<=12; i+=2))
  • I am new to linux so how can I execute the first loop.I know I cannot directly type that in the command line.Could u please tell how to execute the for loop? – John Jan 4 '17 at 10:51
  • @John yes, you can type this in the command line. Just type the lines and when you find a new line, just type Enter! – fedorqui Jan 4 '17 at 10:53
  • Thank u I could not upvote because no enough reputations.Anyway thanks again – John Jan 4 '17 at 11:37
  • @John glad that it worked to you :) – fedorqui Jan 4 '17 at 11:40
0

It is good to see that the indices are just before the file extension.

cat state*.csv > final.csv

considers the sorting by ascii characters. That is, { 6, 8, 10, 12 } on sorting becomes { 10, 12 , 6, 8 }.

In the manual page of ls, there is an option -v, that sorts according to the version number, that is what is required. Therefore, you may use

cat `ls -v | grep .csv` > final.csv

if those are the only csv files in the directory.

0

or more simply

ls -v *.csv | xargs cat >> final.csv

-v order by version number

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.