"+"(一个或多个事件)不与"sed"命令一起使用 [英] '+' (one or more occurrences) not working with 'sed' command
问题描述
我正在尝试通过消除不必要的空格,空行以及使括号之间保持空格来平衡代码的方式来完善我的代码,
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屋!