2013-01-02 82 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 

这迎合了多行嵌套的括号。然而,它可能非常缓慢。