2013-06-04 58 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