簡體   English   中英

如何刪除其中包含特殊字符的行

[英]How to remove the row that has special characters in it

我有一個大文本文件,其中有很多特殊字符,如“$!@%#$ /”加上更多,如果該行中有任何特殊字符,我想刪除文本文件中的行。 我想要保留的唯一字符是az和AZ。

如果這是文件......

!Somejunk)(^%
)%(&_
this
my_file
is
*(%%$
the
they're
file

然后唯一剩下的就是......

this
is
the
file

使用linux命令行工具,bash腳本或python腳本的解決方案會更好,但任何有效的方法都可以!

$ grep '^[[:alpha:]]\+$' << EOF
> !Somejunk)(^%
> )%(&_
> this
> my_file
> is
> *(%%$
> the
> they're
> file
> EOF
this
is
the
file

這似乎有效:

 sed '/[^[:alpha:]]/d' source_file

如果你想只保留帶字母字符的行(如OP請求的那樣),那么:

$ grep -v '[^a-zA-Z]' foo

或者,如果您只想要英文字符:

$ grep -v '[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]' foo

但是如果你只想刪除非字母字符, sed將完成這項工作:

$ cat foo | sed 's/[^a-zA-Z]//g'

或者,如果您只想殺死二進制 ,不可打印的數據,請使用字符串:

$ strings foo

grep -v和一些正則表達式?

比如, egrep -v '[^a-zA-Z]'

您可以使用以下命令過濾掉所需的行:

grep'^ [A-Za-z] \\ + $' 文件

如果您甚至不允許行中的空格,則可以在z之后省略空格。

或者在bash中完全喜歡這樣

#!/bin/bash

file=$(cat file.txt);

for line in $file; do
    if [[ $line =~ ^[a-zA-Z]+$ ]]; then
        echo $line
    fi
done

我將采取真正的nooby方法。

x = open('file','r')
y = x.read().split('\n')
x.close()

for z in range (0, len(y)):
    for a in range (0, len(y[z])):
        if not y[z][a].isalpha() and not y[z][a].isdigit():
            y[z][a] = ''

OutputString = '\n'.join(y)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM