Bash 用于删除 txt 文件中的一些关键字的脚本
Bash script to remove some keywords in a txt file
我不熟悉 bash 脚本,经过一番研究,我找到了一些提示,但仍然需要您的努力。
鉴于我有一个 resources.txt,包含
a
b
c
d
和一个whitelist.txt文件,包含
c
d
我想删除所有从白名单文件到资源文件完全匹配的项目。
所以预期的输出是
a
b
希望 c 和 d 被删除,因为它们在白名单文件中。
我创建了下面的脚本来读取它,但不知道如何将一个一个替换到资源文件中。
# read the whitelist file
echo whitelist.txt | awk '{for (i=1; i<=NF; i++) printf "%s\n",$i}
# replace item in resource file
awk '{sub(/c/,""); print}' resources.txt
非常感谢您的帮助,非常感谢!!
我会使用这个 grep:
grep -Fvxf whitelist.txt resources.txt
-F
fixed/literal 字符串(无正则表达式)
-f FILE
从文件中获取模式
-x
匹配整行
-v
打印不匹配的行
- 这个 grep 是 POSIX
使用awk可以使用
awk 'FNR==NR{a[[=10=]];next}!([=10=] in a)' whitelist.txt resources.txt
部分
awk '
FNR==NR{ # Only for the first file (whitelist.txt)
a[[=11=]] # Set the value of the whole line as a key in a
next # Go to the next record
}
!([=11=] in a) # Print the line if the value of `[=11=]` does not exists as array index in a
' whitelist.txt resources.txt
输出
a
b
我不熟悉 bash 脚本,经过一番研究,我找到了一些提示,但仍然需要您的努力。
鉴于我有一个 resources.txt,包含
a
b
c
d
和一个whitelist.txt文件,包含
c
d
我想删除所有从白名单文件到资源文件完全匹配的项目。 所以预期的输出是
a
b
希望 c 和 d 被删除,因为它们在白名单文件中。
我创建了下面的脚本来读取它,但不知道如何将一个一个替换到资源文件中。
# read the whitelist file
echo whitelist.txt | awk '{for (i=1; i<=NF; i++) printf "%s\n",$i}
# replace item in resource file
awk '{sub(/c/,""); print}' resources.txt
非常感谢您的帮助,非常感谢!!
我会使用这个 grep:
grep -Fvxf whitelist.txt resources.txt
-F
fixed/literal 字符串(无正则表达式)-f FILE
从文件中获取模式-x
匹配整行-v
打印不匹配的行- 这个 grep 是 POSIX
使用awk可以使用
awk 'FNR==NR{a[[=10=]];next}!([=10=] in a)' whitelist.txt resources.txt
部分
awk '
FNR==NR{ # Only for the first file (whitelist.txt)
a[[=11=]] # Set the value of the whole line as a key in a
next # Go to the next record
}
!([=11=] in a) # Print the line if the value of `[=11=]` does not exists as array index in a
' whitelist.txt resources.txt
输出
a
b