我有几百个txt文件,每行有2行。
为了合并它们,我通常会:
cat *.txt > final.txt但是,我只需要对每个文件的第2行这样做,所以最后的输出如下
2nd line of 1st file
2nd line of 2nd file
2nd line of 3rd file
(and so on..)知道我怎么能做到这一点吗?
发布于 2019-03-07 19:14:07
第一解决方案:,请您试着使用GNU awk进行跟踪。nextfile是GNU awk中非常好的选项,当满足条件时,它将跳过当前Input_file中的所有行。
awk 'FNR==2{print;nextfile}' *.txt > output_file第二个解决方案:,以防您没有GNU awk尝试。在这里,由于我们假设在nextfile中没有awk,所以我在每个文件的第2行上创建一个flag,并且当它是真的时,只需运行下一行/跳过它们并尝试保存一些时间。请注意,此标志值也将在每个文件的第一行上重置。
awk 'FNR==1{flag=""} FNR==2{print;flag=1} flag{next}' *.txt > output_file第三种解决方案:在head和tail中也添加了while和find方法。AFAIK头尾不应该读取整个文件。
while read line
do
head -n +2 "$line" | tail -1
done < <(find -type f -name "*.txt") > "output_file"发布于 2019-03-07 19:23:14
与GNU sed:
sed -n -s 2p *.txt > final.txt或
sed -s '2!d' *.txt > final.txt来自man sed
-s:认为文件是独立的,而不是一个连续的长流。
发布于 2019-03-07 19:12:18
find . -name "*.txt" -type f -exec awk 'NR==2' {} \;https://stackoverflow.com/questions/55051127
复制相似问题