How to break a string in a shell script

I have a database name in the following format

username_databasename

Now I want to place separate database backups in the username directory, for example

/backups/username/backup

How can I get usernamae from this line

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

/backups/others/backup
+3
source share
7 answers

You can do:

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

You can use the option:

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

, .

sed - , $(echo | sed) :

username="${fullname%_*}"

.

+3

bash , :

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'

"", IFS = "/" ,

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

cut, grep, sed awk . bash :

db_name=username_databasename

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

script, : -)

+1

awk:

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

bash - ( , , ):

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

if , , . , .

${x%%_*}gives you a line before deleting the longest template _*(in other words, it removes everything from the first underscore to the end).


A (slightly) simpler option:

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

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


All Articles