Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'+' (one or more occurrences) not working with 'sed' command

Tags:

bash

macos

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++   ; 

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?

like image 899
Siddhartha Avatar asked Aug 23 '12 23:08

Siddhartha


People also ask

How do you sed multiple times?

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.

What does sed '/ $/ D do?

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'.

Can you use regex in sed?

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).


1 Answers

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). 
like image 105
Sicco Avatar answered Sep 21 '22 00:09

Sicco