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
This blog covers Unix system administration HOWTO tips for using inline for loops, find command, Unix scripting, configuration, SQL, various Unix-based tools, and command line interface syntax. The Unix OS supports tasks such as running hardware, device drivers, peripherals and third party applications. Share tips/comments. Read the comments. But most importantly: Read Disclaimer - Read Disclaimer.
Subscribe to:
Post Comments (Atom)
6 comments:
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
very nice tip and useful too
@pete
@pinoyskull
I appreciate the comments.
very informative and detailed nix tip, keep up NIX chills!
Good post, appreciate the info, keep up the good work.
@vertito
@dedicated hosting
Glad you found it useful. I'll add some more to this post once I get a break.
Post a Comment