An interview question in unix, which is asked by most of the companies

Well, i was asked a question(which was last one) write a shell script which renames all *.txt files in a directory to *.sh ?

Immediately, mv command came into my mind as it does in many peoples' mind.Then i wrote like:
find . -name "*.txt" -exec mv *.txt *.sh {}\; 
however this was wrong. He told me to explain how the above would work and i realized this was not correct.
then i tried something else like:
find . -name "*.txt" -exec ls {}\; | perl -e '`rename *.txt *.sh`'
I wasn't pretty much sure that this would work.He told thats fine if i could  try without perl.
I asked for some hints and he reminded me of xargs & sh.Then i tried like:
find . -name "*.txt" -exec ls {}\;| xargs -n1 sh -c 'mv $1 `basename $1 .txt`.sh' -
and then i got selected in the unix rounds... :-) :-) 
xargs is really a great unix command like sed & awk.It is quite often used for parallel processing.Never miss this if you  like to play around with shell scripting!

Comments