Saturday, November 10, 2007

Strip an Extension From a Filename - UNIX

I received this common question the other day. "How do I strip an extension from filenames using sed?" Frankly speaking, I thought this howto was already posted in this blog, but after further review, it doesn't appear to be. At any rate, here are some examples starting out with sed. I'm sure others have better ways of performing this task.

Using the sed command to strip an extension
# csh
# ls
t1.dat t2.dat t3.dat t4.dat t5.dat
# foreach filename (*.dat)
? mv $filename `echo $filename | sed 's/.dat//g'`
? end
# ls
t1 t2 t3 t4 t5

Using the basename command to strip an extension
# ls
t1.dat t2.dat t3.dat t4.dat t5.dat
# foreach filename (*.dat)
? mv $filename `basename $filename .dat`
? end
# ls
t1 t2 t3 t4 t5

Using the echo command to strip an extension
# ls
t1.dat t2.dat t3.dat t4.dat t5.dat t6.d1t
# foreach filename (*.dat)
? mv $filename `echo $filename:r`
? end
# ls
t1 t2 t3 t4 t5 t6.d1t

Using a zsh for loop to strip an extension
# ls
t1.dat t2.dat t3.dat t4.dat t5.dat t6.d1t
# zsh
# for filename (*.dat) mv $filename $filename:r
# ls
t1 t2 t3 t4 t5 t6.d1t

Another example using the echo command to strip an extension
# ls
t1.dt3 t2.d67 t3.d79 t4.e67 t5.007 t6.d17
# foreach filename (*.??7)
? mv $filename `echo $filename:r`
? end
# ls
t1.dt3 t2 t3.d79 t4 t5 t6

More examples using the echo command to strip an extension
# ls
t1.110207_org t2.110307_tmp t3.100307 t4.053106 t5.090606 t6.032307 t7.112307_log
# foreach filename (*.11*)
? mv $filename `echo $filename:r`
? end
# ls
t1 t2 t3.100307 t4.053106 t5.090606 t6.032307 t7

# ls
t1.0a t10.aj t2.1b t3.2c t4.3d t5.4e t6.5f t7.6g t8.7h t9.8i
# foreach filename (*.[0-9]?)
? mv $filename `echo $filename:r`
? end
# ls
t1 t10.aj t2 t3 t4 t5 t6 t7 t8 t9

6 comments:

Pete said...

Of course, if you're going to use sed you need to anchor the regex a bit better and escape the '.' to avoid collateral damage...

$ echo mydata samisdat foo.dat | sed -e 's/.dat//g'
ma sami foo

pinoyskull said...

very nice tip and useful too

esofthub said...

@pete
@pinoyskull

I appreciate the comments.

VeRTiTO said...

very informative and detailed nix tip, keep up NIX chills!

Dedicated Hosting said...

Good post, appreciate the info, keep up the good work.

esofthub said...

@vertito
@dedicated hosting

Glad you found it useful. I'll add some more to this post once I get a break.