Home > Mobile >  How do I remove multiple bracket within nested bracket using sed?
How do I remove multiple bracket within nested bracket using sed?

Time:10-10

I want to make a program editing file code with shell programming

there is command 'Remove ${} in arithmetic expansion' and I have a problem in implementation.

I'm going to make bash shell code below

cnt=$(( ${cnt} ${cnt123} ))

to

cnt=$(( cnt cnt123 ))

I want to remove command substitution bracket in arithmetic Expansion bracket

I tried to do with this regex expression:

sed -Ei 's/(\$\(\()([^\)]*?)\$\{([^\}] ?)\}(.*?)(\)\))/\1\2\3\4\5/g' $file

but, it just found a longest one.(even though there are another match before matched one)

if you want to see visualized regex expression, click this link visualized image

result showed like this:

cnt=$(( ${cnt} cnt123 ))

How to do remove internal bracket in nested bracket? (I should just use awk or sed, but if it could be impossible, it doesn't matter using other bash command)

:my sample input file (it doesn't matter what it do for)

#! /bin/bash

cnt=0
cnt123=1
for filename in *
do
        fname=$(basename $filename)
        cname=$(echo $fname | tr A-Z a-z)
        if [ "$fname" !=  "$cname" ] 
        then
                if [ -e "$cname" ]
                then 
                   echo "$cname already exists"
                   exit 1
                fi
                echo "$fname is renamed $cname"
                mv $fname $cname
                cnt=$(( ${cnt}  ${cnt123} ))
        fi
done
echo "Total count: $cnt"
exit 0

works example:

s=$(( ${s} ** 2 )) to s=$(( s ** 2 ))

sum=$(( ${a} ${b} )) to sum=$(( a b ))

echo $(( (${var} * ${var2}) / ${var3} )) to echo $(( (var * var2) / var3 ))

echo ${d} $((${t1} ${t2})) to echo ${d} $(( t1 t2 ))

CodePudding user response:

Depending on the context you may want to limit the extent of the match to only alphanumeric chars

sed -Ei.bak 's/\$\{([[:alnum:]] )\}/\1/g'

to avoid unintentionally matching something else.

CodePudding user response:

Using sed

$ sed -Ei.bak 's/\$\{([^}]*)}/\1/g' input_file
cnt=$(( cnt   cnt123 ))

CodePudding user response:

With your shown samples please try following sed program. Using GNU sed and its -E option to enable ERE(extended regular expression) and then in main program using substitution operation to perform substitution as per requirement. Here is the Online Demo for shown regex.

sed -E 's/^([^{]*)\$\{([^}]*)\}([^{]*)\$\{([^}]*)}(.*)$/\1\2\3\4\5/'  Input_file

Output will be as follows:

cnt=$(( cnt   cnt123 ))
  • Related