连接文件并在文件之间插入新行

我有多个文件,我想与cat 。 我们说

 File1.txt foo File2.txt bar File3.txt qux 

我想连接,以便最终的文件如下所示:

 foo bar qux 

而不是通常的cat File*.txt > finalfile.txt

 foo bar qux 

什么是正确的方法来做到这一点?

    你可以做:

     for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done 

    在运行上述命令之前,请确保文件finalfile.txt不存在。

    如果你被允许使用awk你可以这样做:

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

    如果您没有足够的文件可以列出每个文件,则可以在Bash中使用流程替换 ,在每对文件之间插入一个换行符:

     cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt 

    如果是我这样做,我会使用sed:

     sed -e '$s/$/\n/' -s *.txt > finalfile.txt 

    在这个sed模式中,$有两个含义,首先它只匹配最后一个行号(作为应用模式的行的范围),其次它匹配替换模式中的行的末尾。

    如果你的sed版本没有-s (单独处理输入文件),你可以把它做成循环:

     for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt 

    这就是我在OsX 10.10.3上做的

     for f in *.txt; do (cat $f; echo '') >> fullData.txt; done 

    因为没有参数的简单'echo'命令最后没有插入新的行。

    这在Bash中有效:

     for f in *.txt; do cat $f; echo; done 

    >> (append)”的答案相反,此命令的输出可以传送到其他程序中。

    例子:

    • for f in File*.txt; do cat $f; echo; done > finalfile.txt
    • (for ... done) > finalfile.txt (parens是可选的)
    • for ... done | less for ... done | less (管道变少)
    • for ... done | head -n -1 for ... done | head -n -1 (这剥离了尾随的空行)

    在python中,这与文件之间的空行连接(禁止添加一个额外的空行):

     print '\n'.join(open(f).read() for f in filenames), 

    这里是丑陋的python单线程,可以从shell中调用,并将输出打印到文件中:

     python -c "from sys import argv; print '\n'.join(open(f).read() for f in argv[1:])," File*.txt > finalfile.txt 

    如果你愿意的话,你可以用xargs来做,但主要思想还是一样的:

     find *.txt | xargs -I{} sh -c "cat {}; echo ''" > finalfile.txt