LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   My first shell script ever (https://www.linuxquestions.org/questions/linux-general-1/my-first-shell-script-ever-299495/)

CGameProgrammer 03-09-2005 03:05 AM

My first shell script ever
 
Just wrote my first shell script, though it seems sort of sloppy to me. I wanted to rename 40-50 .html files to .txt, so I read a shell-scripting tutorial, learned a few new Linux commands, and eventually wrote this:
Code:

for F in `ls -a1 *.html`
    do
    wc=`echo -n $F | wc -m`
    len=`expr $wc - 5`
    p="%.`echo $len`s.txt\n"
    name=`printf $p $F`
    mv $F $name
    done

But because you can't nest backquotes, I used a bunch of those temporary variables (which I think looks sloppy) and when setting "p" you'll notice I used backquotes with an echo command, because it couldn't parse "%.$lens.txt\n". But that's an ugly hack IMO.

So, can someone suggest a better way of doing this sort of script?

trevelluk 03-09-2005 03:44 AM

I think this should work.

Code:

#!/bin/bash

for F in `ls -a1 *.html`
    do
    mv $F `basename $F .html`.txt
done


baltho 03-09-2005 03:45 AM

Hi there!!

In my experience, there's always at least a dozen ways to do the same thing in a shell script, so this is just what I'd do, but here goes...

for from in `ls *.html`
do
to=`echo $from | sed -e "s/.html\$/.txt/"`
mv $from $to
done

I find sed quite fiddly to work with, but VERY useful - tweaking the sed command and "echo"ing the mv command until I get it right is how I do it.

Hope it helps......

CGameProgrammer 03-09-2005 09:35 AM

Ah, basename is a very easy way to do it -- wish I'd known about it. :) Never heard of the sed command before, either; I'll have to look up how to use it.

frieza 03-09-2005 09:40 AM

3 usefull commands to learn... i'm still learning them

grep, sed, awk :D

CGameProgrammer 03-09-2005 11:25 AM

I use grep alot, but I've never used those other two.

tokiko 03-11-2005 04:43 PM

you don't even need a shell script; just use the "rename" command :P

rename .html .txt *

CGameProgrammer 03-11-2005 05:17 PM

Wow, lol. Linux has too many obscure commands. :)

AxeZ 03-11-2005 06:30 PM

There is no such thing as "too many"...:)


All times are GMT -5. The time now is 02:12 PM.