0

I currently have this script set up for $1 $2 which takes two inputs, one an extension, one the file name, and searches for the file name in the relative path, if found, replaces the file with the new extension (or does nothing if same extension), and if not found, prints the error message.

#!/bin/csh                                                                      
set ext="$1"
set oldName="$2"
if (-r "$oldName") then
set newName=`echo "$oldName" | sed 's/\.[A-Za-z0-9]*$/'".$ext"'/g'`
if ( "$oldName" == "$newName" ) then
:
else
mv "$oldName" "$newName"
endif
else
echo "$oldName": No such file
endif

What I need is to modify this script so that $1 is always the extension, but $2 can be any number of possible inputs, for example:

./chExt.sh 'bat' 'bool.com' 'nofilefound.biz' 'james.bro'

and would essentially make

bool.bat
nofilefound.biz: No such file
james.bat

so it would always read the $1 as the extension, and always see $2-$n as needing the same processes applied as the original script.

I have to use "foreach"'s and "shifts" specifically.

Zombo
  • 1
  • 62
  • 391
  • 407
  • 2
    Programming in `csh` is considered harmful! See http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/. Try another shell or better yet, a scripting language like `python` or `perl`. – Gowtham Apr 21 '12 at 11:45
  • 1
    You last requirement (using "foreach" and "shift" ) implies that this is homework. If you are taking a course in which csh is recommended for scripting, you should seriously consider the quality of the instruction you are receiving. csh is not suitable for this type of task. – William Pursell Apr 23 '12 at 18:10

1 Answers1

0

In C-Shell, you can $argv[2-] to get an array of parameter 2 and so on. Just put that array in a foreach loop along with the :q modifier to handle spaces in your filenames and you are done.

#!/bin/csh
set ext="$1"

foreach oldName ( $argv[2-]:q )

   if (-r "$oldName") then
       set newName=`echo "$oldName" | sed 's/\.[A-Za-z0-9]*$/'".$ext"'/g'`
       if ( "$oldName" == "$newName" ) then
           :
      else
          mv "$oldName" "$newName"
      endif
  else
      echo "$oldName": No such file
  endif

end

And if you wanted to use shift and foreach, just use the shift to knock the first parameter off the argument list and loop through the remainder:

#!/bin/csh
set ext="$1"

shift
foreach oldName ( $argv )

    set oldName = $1
    if (-r "$oldName") then
        set newName=`echo "$oldName" | sed 's/\.[A-Za-z0-9]*$/'".$ext"'/g'`
        if ( "$oldName" == "$newName" ) then
            :
        else
            mv "$oldName" "$newName"
        endif
    else
        echo "$oldName": No such file
    endif

end
swdev
  • 2,941
  • 2
  • 25
  • 37