“+"(出现一次或多次)不适用于“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屋!