Net Bash Replacement Capture Groups

I have an example line:

test_string="13A6"

These characters / numbers can be from 0 to 9 and from A to F.

I want this output:

1 3 A 6

This works for me:

result=$(echo ${test_string} | sed 's/./& /g')

I want to do this without sed ... and I have another solution that I don't like too much ... dirty: S

[[ ${test_string} =~ ^([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F]) ]] && result="${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]} ${BASH_REMATCH[4]}"

I want, if possible, to use pure bash with the syntax result=${variable//pattern/replacement}, but I'm not sure how to do it, for example, & in sed to refer to the associated char to this kind of pure bash syntax. Any guru bash? :)

+4
source share
2 answers

How about this (without an external utility):

str="13A6"
[[ $str =~ ${str//?/(.)} ]]
printf '%s\n' "${BASH_REMATCH[*]:1}"

Result (without trailing space):

"1 3 A 6"

Or if you need to use a different delimiter:

[[ $str =~ ${str//?/(.)} ]]
( IFS=$'\n'; printf "%s\n" "${BASH_REMATCH[*]:1}")

, IFS :

divide(){ 
    [[ $1 =~ ${1//?/(.)} ]]
    local IFS=${2:-' '}
    printf '%s\n' "${BASH_REMATCH[*]:1}"
}

divide "13A6" "-"            # will output 1-3-A-6 in this example.

:

           ${str//?/(.)}              # Replace each character with "(.)".  
[[ $str =~               ]]           # Match the regex "(.)(.)(.) … …"  
                                      # capturing each character matched  
                                      # in the array "${BASH_REMATCH[@]}"  

printf '%s\n' "${BASH_REMATCH[*]:1}"  # Forget array index 0 and
                                      # convert the array to one string 
                                      # using the first character
                                      # of "$IFS" as separator
                                      # (no trailing separator). 

@chepner @ * . .

+3

, , :

test_string="13A6"
length=$( expr length "$test_string" )
s=""
for (( i=1;i<=${length};i++)) 
do
  c=$( expr substr "${test_string}" $i 1 )
  s=${s}" "$c
done
echo $s

Res:

1 3 A 6

( ) chepner.

test_string="13A6"
s=""
for ((i=0;i<${#test_string};i++))
do
  s=${s}" "${test_string:i:1}
done
echo $s
0

Source: https://habr.com/ru/post/1661763/


All Articles