微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用sed以指定的顺序提取行?

我有一个大约50,000行的文件,我需要检索特定的行。 我已经尝试了以下命令:

sed -n 'Np;Np;Np' inputFile.txt > outputFile.txt

('N'是具体的行,我想提取

这工作正常,但该命令提取ORDER(即它重新命令我的input)ex前面的行。 如果我尝试:

sed -n '200p;33p;40,000p' inputFile.txt > outputFile.txt

我得到一个文本文件,命令为:33,200,40000(这不适合我的目的)。 有没有办法维持命令中显示的行的顺序?

移动Windowsbatch file中的任何打开的应用程序的位置,而不使用nircmd实用程序

如何在batch file或PowerShell脚本中运行命令“x”次?

使用rundll32来复制SUBST的function

将命令的输出分配给variables(BASH)

使用grep和ls -a命令

Windows wget不下载文件,但在浏览器中

如何将某些文件从相同的目录复制到Windows命令提示符中的另一个目录?

获取MysqLpath

Windows'start / b'命令问题

“导出”命令是做什么的?

你必须坚持到第33行,直到看到200行:

sed -n '33h; 200{p; g; p}; 40000p' file

进一步的说明见手册: https : //www.gnu.org/software/sed/manual/html_node/Other-Commands.html

awk可能更具可读性:

awk ' NR == 33 {line33 = $0} NR == 200 {print; print line33} NR == 40000 {print} ' file

如果您有任意数量的行以特定顺序打印,则可以概括如下:

awk -v line_order="11 3 5 1" ' BEGIN { n = split(line_order,inorder) for (i=1; i<=n; i++) linenums[inorder[i]] } NR in linenums {cache[NR]=$0} END {for (i=1; i<=n; i++) print cache[inorder[i]]} ' file

用perl把输入行保存在散列变量中,行号作为键

$ seq 12 20 | perl -nle ' @l = (5,2,3,1); $a{$.} = $_ if( grep { $_ == $. } @l ); END { print $a{$_} foreach @l } ' 16 13 14 12

$. 是行号和grep { $_ == $. } @l grep { $_ == $. } @l检查包含所需行的数组@l是否存在行号

作为BEGIN @l声明,以避免每次迭代都进行初始化,并确保行号超出范围时不会出现空行:

$ seq 50000 > inputFile.txt $ perl -nle 'BEGIN{@l=(200,33,40000)} $a{$.}=$_ if(grep {$_ == $.} @l); END { $a{$_} and print $a{$_} foreach (@l) }' inputFile.txt > outputFile.txt $ cat outputFile.txt 200 33 40000

head和tail组合的解决方案:

$ for i in 200 33 40000; do head -"${i}" inputFile.txt | tail -1 ; done 200 33 40000

输入文件seq 50000 > inputFile.txt 性能比较

$ time perl -nle 'BEGIN{@l=(200,40000)} $a{$.}=$_ if(grep {$_ == $.} @l); END { $a{$_} and print $a{$_} foreach (@l) }' inputFile.txt > outputFile.txt real 0m0.044s user 0m0.036s sys 0m0.000s $ time awk -v line_order="200 33 40000" ' BEGIN { n = split(line_order,inorder) for (i=1; i<=n; i++) linenums[inorder[i]] } NR in linenums {cache[NR]=$0} END {for (i=1; i<=n; i++) print cache[inorder[i]]} ' inputFile.txt > outputFile.txt real 0m0.019s user 0m0.016s sys 0m0.000s $ time for i in 200 33 40000; do sed -n "${i}{p;q}" inputFile.txt ; done > outputFile.txt real 0m0.011s user 0m0.004s sys 0m0.000s $ time sed -n '33h; 200{p; g; p}; 40000p' inputFile.txt > outputFile.txt real 0m0.009s user 0m0.008s sys 0m0.000s $ time for i in 200 33 40000; do head -"${i}" inputFile.txt | tail -1 ; done > outputFile.txt real 0m0.007s user 0m0.000s sys 0m0.000s

你也可以使用其他的bash命令吗? 在这种情况下,这工作:

for i in 200 33 40000; do sed -n "${i}p" inputFile.txt done > outputFile.txt

可能这比在sed中使用数组慢,但更实用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐