加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 使用其他文件中的行号从文本文件中删除行

发布时间:2020-12-14 02:10:58 所属栏目:Linux 来源:网络整理
导读:我有一个文本文件,其中包含一个巨大的行号列表,我必须从另一个主文件中删除.这是我的数据的样子 lines.txt 12452236400... 和documents.txt string1string2string3... 如果我有一个简短的行号列表,我可以轻松使用 sed -i’1d,4d,5d’documents.txt. 但是我必
我有一个文本文件,其中包含一个巨大的行号列表,我必须从另一个主文件中删除.这是我的数据的样子

lines.txt

1
2
4
5
22
36
400
...

和documents.txt

string1
string2
string3
...

如果我有一个简短的行号列表,我可以轻松使用

sed -i’1d,4d,5d’documents.txt.

但是我必须删除很多行号.另外,我可以使用bash / perl脚本将行号存储在数组中,并回显不在数组中的行.但我想知道是否有内置命令来做到这一点.

任何帮助将受到高度赞赏.

解决方法

awk oneliner应该适合你,请看下面的测试:

kent$ head lines.txt doc.txt 
==> lines.txt <==
1
3
5
7

==> doc.txt <==
a
b
c
d
e
f
g
h

kent$ awk 'NR==FNR{l[$0];next;} !(FNR in l)' lines.txt doc.txt
b
d
f
h

正如Levon所说,我补充一些解释:

awk                     # the awk command
 'NR==FNR{l[$0];next;}  # process the first file(lines.txt),save each line(the line# you want to delete) into an array "l"

 !(FNR in l)'           #now come to the 2nd file(doc.txt),if line number not in "l",print the line out
 lines.txt              # 1st argument,file:lines.txt
 docs.txt               # 2nd argument,file:doc.txt

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读