bash Linux:合并多个文件,每个文件换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2576693/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:08:37  来源:igfitidea点击:

Linux: Merging multiple files, each on a new line

linuxbash

提问by Marco

I am using cat *.txtto merge multiple txt files into one, but I need each file to be on a separate line.

我正在使用cat *.txt将多个 txt 文件合并为一个,但我需要每个文件都在单独的行上。

What is the best way to merge files with each file appearing on a new line?

合并每个文件出现在新行上的最佳方法是什么?

回答by ghostdog74

just use awk

只需使用 awk

awk 'FNR==1{print ""}1' *.txt

回答by Such

If you have a pastethat supports it,

如果你有一个paste支持它,

paste --delimiter=\n --serial *.txt

does a really great job

做得很好

回答by R Samuel Klatchko

You can iterate through each file with a for loop:

您可以使用 for 循环遍历每个文件:

for filename in *.txt; do
    # each time through the loop, ${filename} will hold the name
    # of the next *.txt file.  You can then arbitrarily process
    # each file
    cat "${filename}"
    echo

# You can add redirection after the done (which ends the
# for loop).  Any output within the for loop will be sent to
# the redirection specified here
done > output_file

回答by Matthew Flaschen

I'm assuming you want a line break between files.

我假设你想在文件之间换行。

for file in *.txt
do
   cat "$file" >> result
   echo >> result
done

回答by Ignacio Vazquez-Abrams

for file in *.txt
do
  cat "$file"
  echo
done > newfile