更快地合并多个文件的方法

use*_*910 4 linux bash file

我在Linux中有多个小文件(大约70,000个文件),我想在文件的每一行的末尾添加一个单词,然后将它们全部合并到一个文件中.

我正在使用这个脚本:

for fn in *.sms.txt 
do 
    sed 's/$/'$fn'/' $fn >> sms.txt
    rm -f $fn
done
Run Code Online (Sandbox Code Playgroud)

有更快的方法吗?

gni*_*urf 6

我试过这些文件:

for ((i=1;i<70000;++i)); do printf -v fn 'file%.5d.sms.txt' $i; echo -e "HAHA\nLOL\nBye" > "$fn"; done
Run Code Online (Sandbox Code Playgroud)

我尝试了大约4分钟(真实)处理的解决方案.您的解决方案的问题在于您需要sed70000次!分叉很慢.

#!/bin/bash

filename="sms.txt"

# Create file "$filename" or empty it if it already existed
> "$filename"

# Start editing with ed, the standard text editor
ed -s "$filename" < <(
   # Go into insert mode:
   echo i
   # Loop through files
   for fn in *.sms.txt; do
      # Loop through lines of file "$fn"
      while read l; do
         # Insert line "$l" with "$fn" appended to
         echo "$l$fn"
      done < "$fn"
   done
   # Tell ed to quit insert mode (.), to save (w) and quit (q)
   echo -e ".\nwq"
)
Run Code Online (Sandbox Code Playgroud)

这个解决方案花了大约 6秒.

别忘了,ed是标准的文本编辑器,不要忽略它!如果你喜欢ed,你可能也会喜欢ex!

干杯!