Forum Programmation.shell [Bash] Limiter taille substring

Posté par . Licence CC By‐SA.
Étiquettes :
0
13
déc.
2019

Hello tout le monde.

Dans un exemple type de strings comme suit :

[fuse.ssh] /media/myMountPath 411GB / 921GB (42%)
[glusterfs] /media/superStorage 0.5TB / 1.1TB (50%)
[ext42] /hello/world 25KB / 42KB (57%)

J'essaye, en bash, de limiter la taille des substrings afin de les empêcher de sortir de leur container.
Donc question :
Comment faire pour limiter la taille des sous chaines [formatage] et /point/de/montage sans toucher au reste.

  • # Solution

    Posté par . Évalué à 1.

    #!/bin/bash
    function limitSubStringLenght {
     # 1ドル => main string
     # 2ドル => substring pattern (regex)
     # 3ドル => max lenght
     work="1ドル"
     while IFS= read -r result
     do
     # $result contain substring matched
     # save a copy of the cuted version of the substring
     endCut=$(echo $result | cut -c 1-"3ドル")
     # cut the substring in the main string
     work=$(echo -n "$work" | sed "s#$result#$endCut#g")
     # we set the substring to match here
     done < <(echo "1ドル" | grep -Eo "2ドル")
     echo -n "$work"
    }
     # set the example variable
    diskInfos=$(echo -n '[fuser.sshfs] /media/partition/blablabla 1.2GB / 2.4GB')
     # displaying test example before change it
    echo ' BEFORE => '"$diskInfos"
     # apply change and save it in to $diskInfos
    diskInfos=$(limitSubStringLenght "$diskInfos" '(/[a-Z0-9._]{1,}){1,}/{0,}' 20)
     # displaying results
    echo -n ' AFTER_ => '"$diskInfos"

    Ce qui produit :

    └─ $ ▶ ./test.bash 
     BEFORE => [fuser.sshfs] /media/partition/blablabla 1.2GB / 2.4GB
     AFTER_ => [fuser.sshfs] /media/partition/bla 1.2GB / 2.4GB
    

    Enjoy 😉

Suivre le flux des commentaires

Note : les commentaires appartiennent à celles et ceux qui les ont postés. Nous n’en sommes pas responsables.