Extract part of a string without cut/split

From Tuxunix
Jump to: navigation, search
  • ${VAR#pattern} # delete shortest match of pattern from the beginning
  • ${VAR##pattern} # delete longest match of pattern from the beginning
  • ${VAR%pattern} # delete shortest match of pattern from the end
  • ${VAR%%pattern} # delete longest match of pattern from the end

Ex:

 while read i; do
   echo -e "Account: ${i%%,*}\nPwd: ${i##*,}\n"
 done <<EOF
 toto,NO,pwdToto
 titi,NO,pwdTiti
 sano,NO,pwdSano
 sani,NO,pwdSani
 EOF

Result :

#> ./test.sh
Account: toto
Pwd: pwdToto

Account: titi
Pwd: pwdTiti

Account: sano
Pwd: pwdSano

Account: sani
Pwd: pwdSani


Other :

accountname="${!i%%,*}"
password="${!i#*,}"