2013-01-02 80 views
3

在一個字符串中,我試圖用下劃線替換括號中的所有空格。例如,給出this (is my) simple example我想獲得this (_is_my_) simple example只替換括號中的空格

我正在研究bash和爲sed創建替換表達式的想法,但是我無法想出一個簡單的一行解決方案。

期待您的幫助

+6

這個(是(另一個)簡單的例子和​​這個(我的)沒有那麼簡單的例子嗎? – aioobe

+0

這兩個問題都很好。對於我的情況,嵌套的括號並不重要,因爲數據是我已經嘗試了很多非高級sed的東西,這樣做或者導致沒有任何東西或所有的空間被替換。 – joerhau

回答

2

使用SED:

sed ':l s/\(([^)]*\)[ ]/\1_/;tl' input 

如果你有不配對的括弧:

sed ':l s/\(([^)]*\)[ ]\([^)]*)\)/\1_\2/;tl' input 
+0

很好,正是我在尋找的東西。 ... – joerhau

1
$ cat file 
this (is my) simple example 
$ awk 'match($0,/\([^)]+\)/) {str=substr($0,RSTART,RLENGTH); gsub(/ /,"_",str); $0=substr($0,1,RSTART-1) str substr($0,RSTART+RLENGTH)} 1' file 
this (_is_my_) simple example 

把比賽()在一個循環中,如果模式可以在一行中出現多次。

0

使用真正的編程語言:

#!/usr/bin/python 

import sys 

for line in sys.stdin: 
    inp = False 
    for x in line: 
     if x == '(': 
      inp = True 
     elif x == ')': 
      inp = False 
     if inp == True and x == ' ': 
      sys.stdout.write('_') 
     else: 
      sys.stdout.write(x) 

這隻能處理簡單的情況下,但應該很容易擴展到更復雜的情況。

$echo "this (is my) simple case"|./replace.py 
$this (_is_my_) simple case 
$ 
+1

sed是完全的,什麼是真正的編程語言? – aktivb

0

假設沒有出現任何嵌套括號或破碎對括號的,最簡單的方法是使用Perl這樣的:

perl -pe 's{(\([^\)]*\))}{($r=$1)=~s/ /_/g;$r}ge' file 

結果:

this (_is_my_) simple example 
0

這可能會爲你工作(GNU SED):

sed 's/^/\n/;ta;:a;s/\n$//;t;/\n /{x;/./{x;s/\n /_\n/;ta};x;s/\n/\n/;ta};/\n(/{x;s/^/x/;x;s/\n(/(\n/;ta};/\n)/{x;s/.//;x;s/\n)/)\n/;ta};s/\n\([^()]*\)/\1\n/;ta' file 

這迎合了多行嵌套的括號。然而,它可能非常緩慢。