Last active
April 1, 2025 12:54
-
-
Save caruccio/4340471 to your computer and use it in GitHub Desktop.
Path manipulation with bash vars
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ FILE=/some/path/to/file.txt | |
################################### | |
### Remove matching suffix pattern | |
################################### | |
$ echo ${FILE%.*} # remove ext | |
/some/path/to/file | |
$ FILE=/some/path/to/file.txt.jpg.gpg # note various file exts | |
$ echo ${FILE%%.*} # remove all exts | |
/some/path/to/file | |
$ FILE=/some/path/to/file.txt # back to inital value | |
$ echo ${FILE%/*} # dirname (same as "dirname $FILE") | |
/some/path/to | |
$ echo "[ ${FILE%%/*} ]" # enclosing value with [ ] to clarify | |
[ ] # no value at all | |
################################## | |
### Remove matching prefix pattern | |
################################## | |
$ echo ${FILE#/some} # remove root dir only (nice to join paths) | |
/path/to/file.txt | |
$ echo /root/dir/${FILE#/some/path/} # removing prefix path and join to arbitrary prefix dir | |
/root/dir/to/file.txt | |
$ echo ${FILE##*/} # remove all dirs (same as "basename $FILE") | |
file.txt | |
################################## | |
### Check for a given extension | |
################################## | |
$ if [ "${FILE/*.txt/1}" == '1' ]; then | |
> echo match | |
> else | |
> echo nope | |
> fi | |
match | |
$ if [ "${FILE/*.conf/1}" == '1' ]; then | |
> echo match | |
> else | |
> echo nope | |
> fi | |
nope | |
# And here is a nice little function: | |
$ function ext_is() { [ "${1/*.$2/1}" == '1' ]; } | |
$ ext_is $FILE txt && echo match || echo nope | |
match | |
$ ext_is $FILE conf && echo match || echo nope | |
nope |
Thumbs Up :)
I think you have a typo. I believe this:
$ echo ${FILE#/some}
some/path/to/file
should be:
$ echo ${FILE#/some}
/path/to/file
Still, very helpful. Thanks.
Thanks, very helpful!
@grymoire7 Fixed, thanks!
Added: filename extension testing
Thanks, Very Helpful!!
Thanks -> Very useful!
๐
๐
Great collection
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was just what I was looking for. Thanks!