Bash: trim parameter from both ends

Hello!

These are the well-known Bash parameter extension patterns:

$ {parameter # word} , $ {parameter ## word}

and

$ {parameter% word} , $ {parameter %% word}

I need to chop off one part from the beginning and part of the anoter from the completion of the parameter. Could you advise me something for me?

+3
source share
4 answers

If you use Bash version> = 3.2, you can use the regular expression corresponding to the capture group to get the value in one command:

$ path='/xxx/yyy/zzz/ABC/abc.txt'
$ [[ $path =~ ^.*/([^/]*)/.*$ ]]
$ echo ${BASH_REMATCH[1]}
ABC

This will be equivalent to:

$ path='/xxx/yyy/zzz/ABC/abc.txt'
$ path=$(echo "$path" | sed 's|^.*/\([^/]*\)/.*$|\1|p')
$ echo $path
ABC
+1
source

, , , , , . :

> xx=hello_there
> yy=${xx#he}
> zz=${yy%re}
> echo ${zz}
llo_the

:

> zz=$(echo ${xx%re} | sed 's/^he//')
> echo ${zz}
llo_the

, - - , , script .

0

, , - . : %, , ##, , :

$ path=/path/to/my/last_dir/filename.txt

$ dir=${path%/*}     

$ echo $dir
/path/to/my/last_dir

$ dir=${dir##*/}

$ echo $dir
last_dir
0

bash, 3 , .

$ path='/xxx/yyy/zzz/ABC/abc.txt'
$ IFS='/' arr=( $path )
$ echo ${arr[${#arr[@]}-2]}
ABC

This works by telling bash that each element of the array is separated by a forward slash /through IFS='/'. We refer to the penultimate element of the array, first determining how many elements are in the array through ${#arr[@]}, then subtracting 2 and using this as an index to the array.

0
source

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


All Articles