Reputation: 315
Does someone knows the meaning of the code below?
#!/bin/sh
files=`find -name *.conifg`
for i in $files
do
name=${i#*/}
dir=${name%/*}
done
I don't understand the two lines:
name=${i#*/}
dir=${name%/*}
What's the meaning of "#/" and "%/"? Thanks.
Upvotes: 0
Views: 45
Reputation: 289495
This is called Shell Parameter Expansion.
Let's do a test to see its behaviour:
$ mypath="this/is/my/path"
$ echo ${mypath#*/}
is/my/path
$ echo ${mypath%/*}
this/is/my
So
name=${i#*/} -> gets everything from first slash in $i variable.
dir=${name%/*} -> gets everything up to last slash in $name variable.
Taken from the resource:
${parameter#word}
The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case). If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
${parameter%word}
The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
Upvotes: 3