bash 使用bash将目录中的所有文件合并为一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4827453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge all files in a directory into one using bash
提问by Silver Light
I have a directory with several *.js files. Quantity and file names are unknown. Something like this:
我有一个包含多个 *.js 文件的目录。数量和文件名未知。像这样的东西:
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:
我需要将此目录中的所有文件合并为一个merged_dmYHis.js
. 例如,如果文件内容是:
1.js
1.js
aaa
bbb
2.js
2.js
ccc
ddd
eee
blabla.js
blabla.js
fff
The merged_280120111257.js
would contain:
在merged_280120111257.js
将包含:
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?
有没有办法使用 bash 来做到这一点,或者这样的任务需要更高级别的编程语言,比如 python 或类似的?
回答by eumiro
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?
只是出于兴趣 - 您认为将文件命名为 DDMMYYYYHHMM 是个好主意吗?按时间顺序(在 shell 内)对文件进行排序可能很困难。YYYYMMDDHHMM 模式怎么样?
cat *.js > merged_`date +%Y%m%d%H%M`.js
回答by Sami Korhonen
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.
在这个例子中, cat 从 ls 命令中获取文件列表, -t 按时间戳排序, -r 反转默认顺序。