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++ ;
should change to:
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++ ;
Here is my script:
#!/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?
You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.
It means that sed will read the next line and start processing it. nothing will be printed other than the blank lines, three times each. Show activity on this post. The command d is only applied to empty lines here: '/^$/d;p;p'.
The sed command has longlist of supported operations that can be performed to ease the process of editing text files. It allows the users to apply the expressions that are usually used in programming languages; one of the core supported expressions is Regular Expression (regex).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With