basenames in Linux

Posted in robobait at 11:28 am by ducky

I always forget how to do this, and it is incredibly handy…

I frequently want to munge a bunch of files up, and afterwards, change its extension. So for example, I want to do something like

cat a.xml | ./xml2html > a.html

cat b.xml | ./xml2html > b.html


It is really easy to just tack something onto the end in bash:

for x in *.xml; do echo $x; cat $x | ./xml2html > $x.html; done

but that will give me ugly files like a.xml.html, b.xml.html, etc.

The basename command to the rescue!

for x in *.xml; do echo $x; cat $x | ./xml2html > `basename $x .xml`.html; done

(Note1: I like to always to an echo $x as the only part of the for loop to make sure I’m only getting files I mean to.)

(Note2: Yes, yes, xargs is apossibility, but I don’t know off the top of my head how to keep the pipe in the command executed by xargs, and not have the pipe get the output of the xargs. Maybe someday I’ll figure out how to do that and post a robobait on that as well.)

Leave a Comment

Comment moderation is enabled. Your comment may take some time to appear.