从文件中读取多行,行号在另一个文件中给出

Read multiple rows from file, rows numbers given in another file

我知道如何使用 awk 从文件中读取第 n 行:

awk 'NR == 10' myfile.txt

而且效果很好。现在我需要从这个文件中读取多行,行号在另一个文件中给出 myrows.txt:

10
15
25
100

是否可以这样做:

cat myrows.txt | awk 'NR == ?how?' myfile.txt

或者我需要循环吗?

你可以使用这个 awk:

awk 'FNR==NR {a[[=10=]]; next} FNR in a' myrows.txt myfile.txt

解释:

FNR==NR  # for first file populate an array `a` with line numbers as key
next     # keep reading 1st file till EOF is reached
FNR in a # print record from 2nd file if current line # in 2nd file is in array a

您也可以使用 sed

sed -n "$(sed 's/$/p;/' rows.txt)" myfile.txt

内部 sed 命令创建以下脚本

10p;
15p;
25p;
100p;

... 将由外部 sed 命令执行。

顺便说一句,我更喜欢@anubhava 的awk 解决方案。它看起来更干净。但是,这两个命令都在做同样的事情。

您也可以使用 while 循环:

while read line
do
  awk "NR == $line" myfile.txt
done < "myrows.txt"