3

假设我有一个这样的字符串:

Output:   
I have some-non-alphanumeric % characters remain here, I "also, have_+ some & .here"

我只想删除引号内非字母数字字符,逗号、句点或空格除外

Desired Output:    
I have some-non-alphanumeric % characters remain here, I "also, have some  .here"

我尝试了以下sed命令匹配字符串并在引号内删除,但它会删除引号内的所有内容,包括引号:

sed '/characters/ s/\("[^"]*\)\([^a-zA-Z0-9\,\. ]\)\([^"]*"\)//g'

任何帮助表示赞赏,最好使用sed,以获得所需的输出。提前致谢!

4

2 回答 2

2

Sed 不是解决此问题的正确工具。这是通过 Perl 实现的。

perl -pe 's/[^a-zA-Z0-9,.\s"](?!(?:"[^"]*"|[^"])*$)//g' file

例子:

$ echo 'I have some-non-alphanumeric % characters remain here, I "also, have_+ some & .here"' | perl -pe 's/[^a-zA-Z0-9,.\s"](?!(?:"[^"]*"|[^"])*$)//g'
I have some-non-alphanumeric % characters remain here, I "also, have some  .here"

正则表达式演示

于 2015-01-26T03:02:06.377 回答
2

您需要多次重复替换以删除所有非字母数字字符。在 sed 中执行这样的循环需要一个标签并使用bandt命令:

sed '
# If the line contains /characters/, just to label repremove
/characters/ b repremove
# else, jump to end of script
b
# labels are introduced with colons
:repremove
# This s command says: find a quote mark and some stuff we do not want
# to remove, then some stuff we do want to remove, then the rest until
# a quote mark again. Replace it with the two things we did not want to
# remove
s/\("[a-zA-Z0-9,. ]*\)[^"a-zA-Z0-9,. ][^"a-zA-Z0-9,. ]*\([^"]*"\)/\1\2/
# The t command repeats the loop until we have gotten everything
t repremove
'

(即使没有[^"a-zA-Z0-9,. ]*,这也可以工作,但在连续包含许多非字母数字字符的行上会更慢)

尽管另一个答案是正确的,因为在 perl 中执行此操作要容易得多。

于 2015-01-26T03:04:34.420 回答