将第二行 txt 文件合并在一起

Merge 2nd line of txt files together

我有几百个 txt 文件,每个文件有 2 行。

要合并它们,我通常会这样做:

cat *.txt > final.txt

但是,我只需要对每个文件的第二行执行此操作,因此最终输出就像

2nd line of 1st file
2nd line of 2nd file
2nd line of 3rd file
(and so on..)

有什么办法可以实现吗?

find . -name "*.txt" -type f -exec awk 'NR==2' {} \;

使用awk

awk 'FNR == 2 { print; nextfile }' *.txt > final.txt

FNR 包含当前文件中的行号。当它在第 2 行时,它将打印该行,然后转到下一个文件。

第一个解决方案: 能否请您尝试使用 GNU awknextfile 是 GNU awk 中非常好的选项,当满足条件时,它将跳过当前 Input_file 中的所有行。

awk 'FNR==2{print;nextfile}' *.txt > output_file


第二个解决方案: 如果你没有 GNU awk 试试。在这里,因为我们假设 awk 中没有 nextfile,所以我在每个文件的第 2 行创建一个 flag,当它为 TRUE 时,只需继续下一个 line/skipping 并尝试节省时间。请注意,此标志值也将在每个文件的第一行重置。

awk 'FNR==1{flag=""} FNR==2{print;flag=1} flag{next}'  *.txt > output_file


第三个解决方案: 添加 whilefind 方法也在这里 headtail。 AFAIK head 和 tail 不应该读取整个文件。

while read line
do
  head -n +2 "$line" | tail -1 
done <  <(find -type f -name "*.txt") > "output_file"

使用 GNU sed:

sed -n -s 2p *.txt > final.txt

sed -s '2!d' *.txt > final.txt

来自man sed

-s: consider files as separate rather than as a single continuous long stream.

使用 Perl

 perl -ne ' if($.==2) { print ; close(ARGV) } ' *.txt

带有示例文件

$ cat allison1.txt
line1 in file1
line2 in file1

$ cat allison2.txt
line1 in file2
line2 in file2

$ cat allison3.txt
line1 in file3
line2 in file3

$  perl -ne ' if($.==2) { print ; close(ARGV) } ' allison*txt
line2 in file1
line2 in file2
line2 in file3

$