删除文件中包含白名单中字符的行

时间:2014-03-19 22:29:32

标签: bash unix sed

如何删除包含不在白名单中的字符的文件中的所有行?

列入白名单的字符:

A-Z a-z {}!@$%&().,;'"

输入:

the socialist government of josé sócrates
all of that is to be commended.
allow me a final comment {please}
watch tom & jerry

输出:

all of that is to be commended.
allow me a final comment {please}
watch tom & jerry

我试过了sed '/[A-Za-z]{}!@$%&().,;'"/,$d' input,但每个角色都没有匹配..任何帮助?

5 个答案:

答案 0 :(得分:3)

bash中的一个奇怪的技巧是匹配双阴性。在这里,我们只打印 not 中包含 not 字符的行:

pat='A-Z a-z{}!@$%&().,;"'"'"
while read -r; do
  if [[ $REPLY != *[^$pat]* ]]; then
    printf '%s\n' "$REPLY"
  fi
done

在尝试判断某个值是纯数字($var != *[^0-9]*)时更常见,但它也适用于此。

答案 1 :(得分:1)

您可以通过从行中set获得一系列独特字符。然后很容易与白名单进行比较:

from string import ascii_letters

WHITELIST = ascii_letters + ''' {}!@$%&().,;'"'''

with open('myfile.txt') as f, open('newfile.txt', 'w') as f2:
    ok_lines = [line for line in f if set(line.strip()) <= set(WHITELIST)
    f2.writelines(ok_lines)

我们制作新文件的原因是您不能简单地删除一行。我们必须采用我们想要的线,然后重新编写这些线。

答案 2 :(得分:1)

正如您在unix中使用的那样,请尝试使用Perl oneliner:

cat input.txt | perl -ne 'print for /^([A-Za-z{}!@$%&().,;\'"\s]+)$/g;'

使用> output.txt

将输出重定向到任何其他文件

或者,您也可以尝试备份当前文件,然后自动修改:

perl -i.bak -ne "print for /^([A-Za-z{}!@$%&().,;'\"\s]+)$/g;" input.txt

答案 3 :(得分:1)

Python解决方案:

import string

fname = 'myfile.txt'
whitelist = string.ascii_letters + """{}!@$%&(),;'". """

(打破重置荧光笔)

with open(fname) as f:
    for line in f:
        if all((ch in whitelist) for ch in line.strip()):
            print line.rstrip('\n')
# this prints relevant lines to stdout

或作为一个班轮:

print '\n'.join(line for line in txt.splitlines() 
                if all((ch in whitelist) for ch in line ))

答案 4 :(得分:0)

这将创建一个新文件,其中的行只包含白名单中的字符 - Python:

whitelist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
             'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
             's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
             'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
             'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
             'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '{',
             '}', '!', '@', '$', '%', '&', '(', ')', '.',
             ',', ';', '"', "'"]

with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        if not all(c in whitelist for c in line.strip()):
            continue
        outfile.write(line)
相关问题