"+"(一个或多个事件)不与"sed"命令一起使用 [英] '+' (one or more occurrences) not working with 'sed' command

查看:121
本文介绍了"+"(一个或多个事件)不与"sed"命令一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过消除不必要的空格,空行以及使括号之间保持空格来平衡代码的方式来完善我的代码,

I'm trying to refine my code by getting rid of unnecessary white spaces, empty lines, and having parentheses balanced with a space in between them, so:

    int a = 4;
    if ((a==4) ||   (b==5))

    a++   ;

应更改为:

    int a = 4;
    if ( (a==4) || (b==5) )
    a++ ;

它确实适用于方括号和空行.但是,它忘记将多个空间缩小为一个空间:

It does work for the brackets and empty lines. However, it forgets to reduce the multiple spaces to one space:

    int a = 4;
    if ( (a==4) ||   (b==5) )
    a++    ;

这是我的剧本:

    #!/bin/bash
    # Script to refine code
    #
    filename=read.txt

    sed 's/((/( (/g' $filename > new.txt
    mv new.txt $filename

    sed 's/))/) )/g' $filename > new.txt
    mv new.txt $filename

    sed 's/ +/ /g' $filename > new.txt
    mv new.txt $filename

    sed '/^$/d' $filename > new.txt
    mv new.txt $filename

还有一种方法可以使此脚本更简洁,例如删除或减少命令数量?

Also, is there a way to make this script more concise, e.g. removing or reducing the number of commands?

推荐答案

如果使用的是 GNU sed ,则需要使用sed -r强制sed使用扩展的正则表达式,包括+的所需行为.参见man sed:

If you are using GNU sed then you need to use sed -r which forces sed to use extended regular expressions, including the wanted behavior of +. See man sed:

-r, --regexp-extended

       use extended regular expressions in the script.

如果使用的是 OS X sed ,则保持不变,但随后需要使用sed -E:

The same holds if you are using OS X sed, but then you need to use sed -E:

-E      Interpret regular expressions as extended (modern) regular expressions
        rather than basic regular regular expressions (BRE's).

这篇关于"+"(一个或多个事件)不与"sed"命令一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆