Silver Light
Silver Light

Reputation: 45902

Merge all files in a directory into one using bash

I have a directory with several *.js files. Quantity and file names are unknown. Something like this:

js/
 |- 1.js
 |- 2.js
 |- blabla.js

I need to merge all the files in this directory into one merged_dmYHis.js. For example, if files contents are:

1.js

aaa
bbb

2.js

ccc
ddd
eee

blabla.js

fff

The merged_280120111257.js would contain:

aaa
bbb
ccc
ddd
eee
fff

Is there a way to do it using bash, or such task requires higher level programming language, like python or similar?

Upvotes: 22

Views: 33429

Answers (2)

Sami Korhonen
Sami Korhonen

Reputation: 21

You can sort the incoming files as well, the default is alphabetical order, but this example goes through from oldest to the newest by the file modification timestamp:

cat `ls -tr *.js` > merged_`date +%Y%m%d%H%M`.js

In this example cat takes the list of files from the ls command, and -t sorts by timestamp, and -r reverses the default order.

Upvotes: 1

eumiro
eumiro

Reputation: 212835

cat 1.js 2.js blabla.js > merged_280120111257.js

general solution would be:

cat *.js > merged_`date +%d%m%Y%H%M`.js

Just out of interest - do you think it is a good idea to name the files with DDMMYYYYHHMM? It may be difficult to sort the files chronologically (within the shell). How about the YYYYMMDDHHMM pattern?

cat *.js > merged_`date +%Y%m%d%H%M`.js

Upvotes: 69

Related Questions