Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge all files in a directory into one using bash

Tags:

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?

like image 844
Silver Light Avatar asked Jan 28 '11 10:01

Silver Light


People also ask

How do I combine multiple files into one in Linux?

Appending content to an existing file To append content after you merge multiple files in Linux to another file, use double redirection operator. (>>) along with cat command. Rather than overwriting the contents of the file, this command appends the content at the end of the file.

How do I combine files into one?

Open the two files you want to merge. Select all text (Command+A/Ctrl+A) from one document, then paste it into the new document (Command+V/Ctrl+V). Repeat steps for the second document. This will finish combining the text of both documents into one.


2 Answers

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
like image 134
eumiro Avatar answered Sep 24 '22 15:09

eumiro


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.

like image 32
Sami Korhonen Avatar answered Sep 21 '22 15:09

Sami Korhonen