Geekblok

B10m, BOK, Joffie - old geeks on a blog

Entries Comments



shell tips and trick, part 2

19 January, 2008 (13:31) | guides, technical | By: Joffie

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:
$ I=/home/joffie/geekblok.txt; echo ${I%/*}
/home/joffie
The description from the man page of basename is: strip directory and suffix from filenames. So for example:
$ basename /home/joffie/geekblok.txt
geekblok.txt
The same can be accomplished with:
$ I=/home/joffie/geekblok.txt; echo ${I##*/}
geekblok.txt
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:
$ I=/home/joffie/geekblok.txt; J=${I##*/}; echo ${J%.txt}
geekblok
Bash can also be used when searching and replacing. Take a look at:
$ I=/home/joffie/geekblok.txt; echo ${I/geek/cool}
coolblok.txt
More info can be found in the parameter expansion section of the man page of bash.

Comments

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/ [...]

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.

Write a comment





Preview: