anl*_*rye 7 command-line bash text-processing
我有两个文本文件,我想逐行读取 file1,在 file2 中搜索同一行并将其从 file2 中删除。
我有以下伪代码:
for line in file1.txt
do
sed search line and delete in file2.txt
done
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以使用 grep 完成此操作。
下面是一个例子:
$ echo localhost > local_hosts
$ grep -v -f local_hosts /etc/hosts
127.0.1.1 ubuntu
# The following lines are desirable for IPv6 capable hosts
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
Run Code Online (Sandbox Code Playgroud)
通常,您希望保留file2中实际上不在 file1 中的行。
这些还有更多的可能,
comm <(sort file1) <(sort file2) -23
Run Code Online (Sandbox Code Playgroud)
通过加入
join -v 1 <(sort file1) <(sort file2)
Run Code Online (Sandbox Code Playgroud)
或通过不需要对文件进行排序的AWK:
awk 'NR==FNR{lines[$0];next} !($0 in lines)' file2 file1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8123 次 |
| 最近记录: |