开发者

How to break the string in shell script

开发者 https://www.devze.com 2023-01-19 23:22 出处:网络
I have the databases name in 开发者_运维百科following format username_databasename Now I want to put separate database backups in username directory like

I have the databases name in 开发者_运维百科following format

username_databasename

Now I want to put separate database backups in username directory like

/backups/username/backup

How can I get the usernamae from that string

I also want that if string does not contain underscore (_) then the backup should go to

/backups/others/backup


You can do:

username=others
if echo $name | grep '_'; then
 username=$(echo $name | cut -d'_' -f 1)
fi


Jonathan Leffler has a nice, clean answer.

If you don't want to use sed for some reason, you can replace the $(echo | sed) bit with:

username="${fullname%_*}"

which does the same thing.


You could use a variation on:

case $fullname in
(*_*) username=$(echo $fullname | sed 's/_.*//');;
(*)   username=others;;
esac
backupdir="/backups/$username/backup"


In bash, you can use arrays, like so:

str="a/bc/def"
IFS="/" arr=($str)
echo ${arr[0]}; # prints 'a'
echo ${arr[1]}; # prints 'bc'
echo ${arr[2]}; # prints 'def'

echo ${arr[@]}; # prints 'a bc def'

If you want to split the string by a different "separator", just change IFS="/" line to that separator, eg

str="a,bc,def"
IFS="," arr=($str)


No need for cut, grep, sed or awk here. Just use bash's inbuilt parameter substitution:

db_name=username_databasename

username=others
if [[ ${db_name} =~ '_' ]]; then
   username=${db_name%%_*} 
fi
backup_dir=/backups/${username}/backup

I prefer to stick to just one language per script, with as few forks as possible :-)


you can use awk:

username = `echo $name | awk -F"_" '{print $1}'`


For a bash-only solution with no potentially expensive calls to external programs (only important if you do it a lot, which may not be the case here):

pax> export x=a ; if [[ "${x%%_*}" != "${x}" ]]; then
...>    export bkpdir=/backups/${x%%_*}/backup
...> else
...>    export bkpdir=/backups/others/backup
...> fi
pax> echo "     ${bkpdir}"
     /backups/others/backup

pax> export x=a_b ; if [[ "${x%%_*}" != "${x}" ]]; then
...>    export bkpdir=/backups/${x%%_*}/backup
...> else
...>    export bkpdir=/backups/others/backup
...> fi
pax> echo "     ${bkpdir}"
     /backups/a/backup

The if statement detects if there's an underscore by checking a modified string against the original. If there is an underscore, they will be different.

The ${x%%_*} gives you the string up to the removal of the longest _* pattern (in other words, it deletes everything from the first underscore to the end).


A (slightly) simpler variant would be:

export bkpdir=/backups/others/backup
if [[ "${x%%_*}" != "${x}" ]]; then
    export bkpdir=/backups/${x%%_*}/backup
fi
0

精彩评论

暂无评论...
验证码 换一张
取 消