仅在括号之间替换空格

时间:2013-01-02 22:34:22

标签: regex bash sed awk

在字符串中,我试图用下划线替换括号中的所有空格。例如,给定this ( is my ) simple example我想获得this (_is_my_) simple example

我正在研究bash,并考虑为sed创建一个替换表达式,但是我无法想出一个简单的单行解决方案。

期待您的帮助

5 个答案:

答案 0 :(得分:6)

使用sed:

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

如果您有不平衡的括号:

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

答案 1 :(得分: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

如果模式可以在一行上多次出现,则将match()放在循环中。

答案 2 :(得分: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
$

答案 3 :(得分:0)

假设没有嵌套的括号或破坏的括号对,最简单的方法是使用Perl这样:

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

结果:

this (_is_my_) simple example

答案 4 :(得分: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

这适用于多行嵌套的parens。然而,这可能非常缓慢。

相关问题