Linux 实用程序逐行交错两个文件的内容

Ars*_*ngh 0 linux bash

我编写了一个脚本来交织两个文件的内容。脚本是这样的

#!/bin/bash

touch t_10.txt

numer1=$(cat $1 | wc -l)
numer2=$(cat $2 | wc -l)

count=1
while [ $count -le $numer1 -a $count -le $numer2 ]
    do
        head -n $count $1 | tail -n 1 >> merge.txt
        head -n $count $2 | tail -n 1 >> merge.txt
        count=$((count + 1))
done

count=$((count-1))
if [ $count -lt $numer1 ]; then
    rem=$(( $numer1 - $count ))
    tail -n $rem $1 >> merge.txt
else
    rem=$(( $numer2 - $count ))
    tail -n $rem $2 >> merge.txt
fi
Run Code Online (Sandbox Code Playgroud)

你能告诉我是否有更好的 cli 实用程序?

Ed *_*ton 5

请阅读为什么使用 shell-loop-to-process-text-considered-bad-practiceshell发明创建/销毁文件和进程以及对工具进行序列调用的人也发明awkshell调用来操作文本。

 $ head file{1,2}
==> file1 <==
foo 1
foo 2
foo 3
foo 4
foo 5

==> file2 <==
BAR 1
BAR 2
BAR 3
Run Code Online (Sandbox Code Playgroud)

$ cat tst.awk
BEGIN {
    file2 = ARGV[2]
    ARGV[2] = ""
    ARGC--
}
{ print }
(getline < file2) > 0
END {
    while ( (getline < file2) > 0 ) {
        print
    }
}
Run Code Online (Sandbox Code Playgroud)

$ awk -f tst.awk file1 file2
foo 1
BAR 1
foo 2
BAR 2
foo 3
BAR 3
foo 4
foo 5
Run Code Online (Sandbox Code Playgroud)

$ awk -f tst.awk file2 file1
BAR 1
foo 1
BAR 2
foo 2
BAR 3
foo 3
foo 4
foo 5
Run Code Online (Sandbox Code Playgroud)

这是适合使用 的极少数情况之一getline,请参阅http://awk.freeshell.org/AllAboutGetline