我有两个文本文件。这两个文件的结构是相同的。我有一个 while 循环,可以同时从这两个文本文件中读取。但是这两个文件,前4行是不需要的。所以我需要的是,在我的程序开始时,两个头将跳到这两个文件的第 4 行,然后开始读取我的 while 循环。这是我当前的代码
while read compareFile1 <&3 && read compareFile2 <&4; do
echo $compareFile1
echo $compareFile2
done 3<test1.txt 4<test2.txt
这是我的示例文件..
=== Predictions on test data ===
inst# actual predicted error prediction (id)
1 1:positive 1:positive 0.774 (10001996.txt)
2 1:positive 2:negative + 0.889 (10003432.txt)
3 1:positive 1:positive 1 (10003865.txt)
4 1:positive 1:positive 0.999 (10004065.txt)
5 1:positive 1:positive 0.991 (10004266.txt)
6 1:positive 1:positive 0.999 (10006157.txt)
7 1:positive 1:positive 0.869 (10007003.txt)
8 1:positive 2:negative + 1 (10008447.txt)
9 1:positive 1:positive 0.998 (10009702.txt)
10 1:positive 1:positive 0.994 (10011072.txt)
我怎样才能通过 bash 做到这一点?我正在使用苹果电脑。谢谢。
tail
实用程序。默认情况下,它输出文件的最后 10 行,但它也有一些非常有用的参数。要跳过前 X 行,请使用 -n+X
。
例:
tail -n+5 myfile.txt
将从第 5 行输出整个文件(跳过前 4 行(。
但在您的情况下,您可以简单地增加一个变量以在第 4 行开始处理。例:
l=0
while read compareFile1 <&3 && read compareFile2 <&4; do
if [[ $l < 4 ]]; then
l=$((l+1));
else
# do your processing here
echo $compareFile1
echo $compareFile2
fi
done 3<test1.txt 4<test2.txt
这是另一种选择,它避免在 shell 循环中读取两个文件:
nl File1.txt | paste - File2.txt | sed -n '5,$ p'
它在第一列中生成行号(通过nl
(,然后是第一个文件的内容,然后是第二个文件的内容。sed
命令删除前四行。
您可以插入awk
并从文件中访问字段,而不是sed
。
根据文件大小,这可能会更快。
要读取除 myfile 的前 4 行之外的所有内容: 尾巴 -n +4 我的文件