Skip to content

Instantly share code, notes, and snippets.

@caruccio
Last active December 28, 2023 22:47
Show Gist options
  • Save caruccio/4340471 to your computer and use it in GitHub Desktop.
Save caruccio/4340471 to your computer and use it in GitHub Desktop.
Path manipulation with bash vars
$ 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
@stuartcw
Copy link

stuartcw commented Nov 6, 2013

This was just what I was looking for. Thanks!

@iazel
Copy link

iazel commented Jan 12, 2014

Thumbs Up :)

@grymoire7
Copy link

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.

@icohen
Copy link

icohen commented Apr 30, 2014

Thanks, very helpful!

@caruccio
Copy link
Author

caruccio commented May 8, 2014

@grymoire7 Fixed, thanks!

@caruccio
Copy link
Author

caruccio commented May 8, 2014

Added: filename extension testing

@npchandran
Copy link

Thanks, Very Helpful!!

@aang7
Copy link

aang7 commented May 22, 2016

Thanks -> Very useful!

@willis7
Copy link

willis7 commented Mar 1, 2017

👍

@cheerfyt
Copy link

👍

@ibnishak
Copy link

Great collection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment