2013-06-04 60 views
0

我一直在尝试sooooo许多不同的变化来获得这种权利。删除包含反斜杠的所有单词

我只是希望使用sed删除所有以反斜杠开头或包含反斜杠的单词。

所以串

another test \/ \u7896 \n test ha\ppy 

将成为

another test test 

我试过洙许多不同的选择,但它似乎没有想工作。有人有一个想法如何做到这一点?

在大家开始给我减1这个问题之前,相信我,我试图找到答案。

回答

2
$ echo "another test \/ \u7896 \n test ha\ppy" | sed -r 's/\S*\\\S*//g' | tr -s '[:blank:]' 
another test test 
+1

您可以添加一个'| tr -s'''删除多个空格。 – fedorqui

+1

@fedorqui对,我注意到你的评论=时已经添加了它)。谢谢。 – kirelagin

3

你可以使用str.splitlist comprehension

>>> strs = "another test \/ \u7896 \n test ha\ppy" 
>>> [x for x in strs.split() if '\\' not in x] 
['another', 'test', 'test'] 

# use str.join to join the list 
>>> ' ' .join([x for x in strs.split() if '\\' not in x]) 
'another test test' 
+0

IM实际上是寻找一个sed命令做这是因为它是os.command optiom的一部分,我的查询很长。功能几个sed的和grep的 –

+3

@ RHK-S8那么这是什么[tag:python]在你的问题做? – kirelagin

0
string = "another test \/ \u7896 \n test ha\ppy"    
string_no_slashes = " ".join([x for x in string.split() if "\\" not in x]) 
1

这可能为你工作(GNU SED):

sed 's/\s*\S*\\\S*//g' file