[英]How can I delete specific lines using awk/sed based on the contents of another file
如何根据另一个文件中包含的行号从文件中删除特定行? 我知道如何仅通过在命令行上提供来删除特定行,但是我不知道如何基于另一个文件中包含的行号来删除特定行。 包含行号的文件采用以下格式:
15768
15775
15777
15782
15784
15789
15791
15798
15800
15807
15809
15815
15817
15824
15826
我总共需要删除2073行。 尽管我无法找到类似的示例,但我一直在尝试搜索操作方法。
谢谢你的帮助。
假设要删除的行号在要删除的文件中to-be-deleted
而数据在big-data-file
,则使用Bash 进程替换 :
sed -f <(sed 's/$/d/' to-be-deleted) big-data-file > smaller-data-file
内部的sed 's/$/d'
命令将行号转换为sed
删除操作。 外部sed
命令读取删除命令,并将操作应用于大数据文件。
使用awk:
awk 'FNR==NR{a[$0];next} !(FNR in a)' f1 f2
ed
是标准编辑器。
可以驱动ed
进行编辑(就地):
#!/bin/bash
ed -s file < <(
while read line; do
[[ $line =~ ^[[:digit:]]+$ ]] || continue
printf "%d d\n" "$line"
done < lines
echo "wq"
)
这将打开带有ed
的文件file
,读取包含行号的文件lines
,检查每个读取的行的确是一个数字,然后向ed
命令删除该数字,并在完成所有操作后要求ed
编写并退出wq
。
您可能想要替换[[ $line =~ ^[[:digit:]]+$ ]] || continue
[[ $line =~ ^[[:digit:]]+$ ]] || continue
按:
[[ $line =~ ^[[:digit:]]+$ ]] || { printf >&2 "*** WARNING: Line %d not deleted\n" "$line"; continue; }
当文件lines
中出现无效行时发出警告。
确保您阅读了glenn jackmann的评论:
我听说
ed
一些较旧的实现不将wq
作为单个命令接受:printf "%s\\n" wq
YMMV。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.