Manipulation de chaîne de caractères en bash
Rédigé par BeHuman
2 commentaires
Classé dans : Shell/Bash

Il m'arrive souvent de devoir extraire une sous chaine d'une chaine de cractères. Pour cela il existe une panoplie d'outils permettant de le faire en ligne de commande. Cependant j'aime me créer mes propres scripts suivant ma logique quotidienne .
Aide:
~$ str
STR version 0.1 by BeHuman
GNU/GPL v3
Usage:
str [OPTION] [PARAMS]
Options:
-h Help
-l At left
-pl At primary left
-r At right
-pr At primary right
-b Between two strings
-R String replace
-len Length
-ler Length Ereg
-p At position
Examples:
str -l "hello world" "o*"
return "hello w"
str -pl "hello world" "o*"
return "hell"
str -r "hello world" "*o"
return "rld"
str -pr "hello world" "*o"
return " world"
str -b "hello world" "*e" "o*"
return "llo w"
str -R "hello world" "ell" "a"
return "hao world"
str -len "hello world"
return 11
str -ler "hello world" 'h[a-z]*.w'
return 7
str -p "hello world" "or"
return 7
Script bash:
#!/bin/bash function _help () { echo "STR version 0.1 by BeHuman GNU/GPL v3 Usage: str [OPTION] [PARAMS] Options: -h Help -l At left -pl At primary left -r At right -pr At primary right -b Between two strings -R String replace -len Length -ler Length Ereg -p At position Examples: str -l \"hello world\" \"o*\" return \"hello w\" str -pl \"hello world\" \"o*\" return \"hell\" str -r \"hello world\" \"*o\" return \"rld\" str -pr \"hello world\" \"*o\" return \" world\" str -b \"hello world\" \"*e\" \"o*\" return \"llo w\" str -R \"hello world\" \"ell\" \"a\" return \"hao world\" str -len \"hello world\" return 11 str -ler \"hello world\" 'h[a-z]*.w' return 7 str -p \"hello world\" \"or\" return 7" } #functions function length () #Length { str=$1 echo ${#str} } function ereg_length () #length ereg { expr match "$1" "$2" } function position_str () #index { str1="$1" pat=$2 str="${str1%%$pat*}" [[ $str = $str1 ]] && echo -1 || echo ${#str} } function left_str () #left { str="$1" pat=$2 echo "${str%$pat}" } function right_str () #right { str="$1" pat=$2 echo "${str##$pat}" } function pleft_str () #left { str="$1" pat=$2 echo "${str%%$pat}" } function pright_str () #right { str="$1" pat=$2 echo "${str#$pat}" } function between_str () #right { str1="$1" pat1=$2 pat2=$3 str2="${str1#$pat1}" echo "${str2%$pat2}" } function replace_str () #right { str="$1" pat1=$2 pat2=$3 echo "${str//$pat1/$pat2}" } #Main Start if [ "$1" == "-h" ];then _help elif [ $# -ge 1 ]; then if [ "$1" == "-len" ];then length "$2" elif [ "$1" == "-ler" ];then ereg_length "$2" "$3" elif [ "$1" == "-b" ];then between_str "$2" "$3" "$4" elif [ "$1" == "-l" ];then left_str "$2" "$3" elif [ "$1" == "-r" ];then right_str "$2" "$3" elif [ "$1" == "-pl" ];then pleft_str "$2" "$3" elif [ "$1" == "-pr" ];then pright_str "$2" "$3" elif [ "$1" == "-p" ];then position_str "$2" "$3" elif [ "$1" == "-R" ];then replace_str "$2" "$3" "$4" else _help fi else _help fi
voilà donc pour ce petit script. ++