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
You may use:
sed 's/[0-9]\./&\\/g' <<< "$branch"
3.\2.\5
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.
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
Varible expansion
branch="3.2.5"
echo ${branch//./.\\}
3.\2.\5
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