shell tips and trick, part 2
This trick is a bit bash specific instead of a real shell trick. On most unix systems you’ll find the commands dirname and basename. These are rather useless when you have got bash. First we’ll look at dirname.
The manual page of dirname states: dirname - strip non-directory suffix from file name. In bash this would be accomplished by parameter expansion:
The manual page of dirname states: dirname - strip non-directory suffix from file name. In bash this would be accomplished by parameter expansion:
$ I=/home/joffie/geekblok.txt; echo ${I%/*}The description from the man page of basename is: strip directory and suffix from filenames. So for example:
/home/joffie
$ basename /home/joffie/geekblok.txtThe same can be accomplished with:
geekblok.txt
$ I=/home/joffie/geekblok.txt; echo ${I##*/}The suffix part of the basename command can be done in two steps. What the command basename does is strip something from both sides of the string. So stripping suffix .txt from $I too:
geekblok.txt
$ I=/home/joffie/geekblok.txt; J=${I##*/}; echo ${J%.txt}Bash can also be used when searching and replacing. Take a look at:
geekblok
$ I=/home/joffie/geekblok.txt; echo ${I/geek/cool}More info can be found in the parameter expansion section of the man page of bash.
coolblok.txt
Comments
Comment from B10m
Time: January 19, 2008, 8:01 pm
I truly wonder how many people would use `sed` for this, like:
I=/home/joffie/geekblok.txt; A=`echo $I | sed -e ’s/geek/cool/’`; echo $A
I love the bash way though! Makes it so much easier and faster.
Pingback from UNIX Coding School » Blog Archive » unix tips [2008-01-19 14:58:08]
Time: January 19, 2008, 4:10 pm
[...] shell tips and trick, part 2 By Joffie On most unix systems you’ll find the commands dirname and basename. These are rather useless when you have got bash. First we’ll look at dirname. The manual page of dirname states: dirname - strip non-directory suffix from file name. … Geekblok - http://geekblok.com/ [...]