【问题标题】:remove spaces between specific characters, with adjacent occurrences删除相邻出现的特定字符之间的空格
【发布时间】:2019-01-22 09:25:33
【问题描述】:

当两个感叹号“!”之间出现空格时,我正在尝试删除它们。

例如,我试过:

echo 'this is ! a repeated ! ! ! ! character ! ! ! here ! !' | sed 's/! !/!!/g'

期望的输出是:

this is ! a repeated !!!! character !!! here !!

但我得到了这个:

this is ! a repeated !! !! character !! ! here !!

一种方法是重复sed 命令,但实际上我可以有任意数量的“!”在我的输入中,我想不出一个干净的方法来做到这一点。

【问题讨论】:

  • 使用条件跳转直到不再发生替换。看看 sed 的 t: 命令。

标签: regex string bash sed replace


【解决方案1】:

使用sed 你可以做一个循环:

echo 'this is ! a repeated ! ! ! ! character ! ! ! here ! !' |
sed -e :a -e 's/! !/!!/g;ta'

this is ! a repeated !!!! character !!! here !!

【讨论】:

    【解决方案2】:

    使用 Perl 的环视断言:

     perl -pe 's/!\s+(?=!)/!/g' 
    

    (?=!) 的意思是“后跟一个感叹号,但不要在匹配的字符串中包含感叹号,并在它之前开始下一个匹配之前”。

    【讨论】:

      猜你喜欢
      • 2021-10-18
      • 2014-07-20
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 2013-12-08
      • 2018-05-15
      • 1970-01-01
      • 2018-04-24
      相关资源
      最近更新 更多