Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a character after a digit and dot in bash

Tags:

bash

shell

sed

awk

I want to modify my a variable by adding \ between any digit and the dot just before it, So far I only managed to add the \ after the first digit and the first dot.

My script:

branch="3.2.5"
firstbranch=$(echo $branch | sed -r 's/([0-9]+.)(.)/\1\\2/g') && echo $firstbranch

the output it generates:

3.\2.5

and the desired output:

3.\2.\5
like image 760
Shahar Hamuzim Rajuan Avatar asked Oct 11 '20 14:10

Shahar Hamuzim Rajuan


4 Answers

You may use:

sed 's/[0-9]\./&\\/g' <<< "$branch"
3.\2.\5
like image 175
anubhava Avatar answered Nov 15 '22 07:11

anubhava


In case you are ok with awk, could you please try following, written and tested with shown samples in link https://ideone.com/T1suTg

echo "$branch" | awk 'BEGIN{FS=".";OFS=".\\"} {$1=$1} 1'

Explanation: Printing shell variable branch value with echo and sending its output as standard input to awk command. In awk program in BEGIN block setting field separator as . and setting output field separator as .\\ which is actually .\ Then in main program re-setting 1st field to itself so that new value of output field separator get applies. 1 will print value of current line.

like image 37
RavinderSingh13 Avatar answered Nov 15 '22 06:11

RavinderSingh13


Also, it is possible to use POSIX BRE expression with sed to insert \ between a dot and a digit:

branch="3.2.5"
firstbranch=$(echo $branch | sed 's/\(\.\)\([[:digit:]]\)/\1\\\2/g') && echo $firstbranch

Result: 3.\2.\5

See online proof.

Regex Explanation

--------------------------------------------------------------------------------
  \(                        group and capture to \1:
--------------------------------------------------------------------------------
    \.                       '.'
--------------------------------------------------------------------------------
  \)                        end of \1
--------------------------------------------------------------------------------
  \(                        group and capture to \2:
--------------------------------------------------------------------------------
    [[:digit:]]              any character of: digits (like \d)
--------------------------------------------------------------------------------
  \)                        end of \2
like image 26
Ryszard Czech Avatar answered Nov 15 '22 06:11

Ryszard Czech


Varible expansion

branch="3.2.5"
echo ${branch//./.\\}
3.\2.\5
like image 30
Ivan Avatar answered Nov 15 '22 07:11

Ivan