How to insert character after first byte into string in Linux

I have the status of the settings file 1,2,3, meaning placement ,after the first, second and third bytes .

For example, my input

stackoverflow

then i want to do it

s,t,a,ckoverflow

How can I do this with Linux tools? I feel that it sedshould be used, but I do not know how to do it.

Edit:

I have over 10 commas. And the string also contains multibyte characters.

+4
source share
4 answers

In sed:

echo stackoverflow | sed 's/./&,/1;s/./&,/3;s/./&,/5'

s/.../.../nreplaces the nth match. After the first replacement, the second byte will now be the third, and after that the third byte will now be the fifth.

, :

echo stackoverflow | sed 's/\(.\)\(.\)\(.\)/\1,\2,\3,/'

Basic Regular Expressions (BRE) \(…\). , n- , \n, , . , , ..

GNU sed \ (ERE):

echo stackoverflow | sed -r 's/(.)(.)(.)/\1,\2,\3,/'

C:

$ echo 'æ  ' | LC_ALL=C sed 's/\(.\)\(.\)\(.\)/\1,\2,\3,/'
 , , , 
$ echo → | LC_ALL=C sed 's/\(.\)\(.\)\(.\)/\1,\2,\3,/'
 , , ,
+1
IFS=, read -ra arr <<< "$1"
rules=()
for i in "${arr[@]}"; do
    rules[$i]=1
done

s=stackoverflow
for (( i=0; i<${#s}; i++ )); do
    if (( ${rules[i+1]} )); then
        printf '%s,' "${s:i:1}"
    else
        printf '%s' "${s:i:1}"
    fi
done

:

$ ./sof 1,2,3
$ s,t,a,ckoverflow
$ ./sof 1,2,3,7
$ s,t,a,ckov,erflow
+1

(GNU sed):

sed 's/\B/\n/g;s/\n//4g;s/\n/,/g' file

sed 's/\B/,/;s/\B/,/;s/\B/,/' file
+1

sed, 10 .

S="♥stackoverflow"
I="1,2,11"
i=0
for j in `echo $I | tr ',' '\n'`; do
   printf ${S:i:j-i}
   i=$j
done
printf ${S:i}

script :

♥,s,tackoverf,low

I="1,2,3,4,5,6,7,8,9,10,11" :

♥,s,t,a,c,k,o,v,e,r,f,low
0

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


All Articles