[techtalk] Stumped by shell script

Almut Behrens almut_behrens at yahoo.com
Tue May 29 05:58:27 EST 2001


On Mon, May 28, 2001 at 04:31:41PM -0700, Nancy Corbett wrote:
> 
> This is off topic, but I'm hoping your sharp eyes will see what I am
> obviously missing.
> 
> I'm writing a ksh script which I want to give 3 variables and read them
> from standard input.  To do this, I'm using sed.  I want sed to
> change every instance of DATE to the current date in a given file
> and rename the file to a different directory. 
> 
> Here's my script:
> 
> #!/bin/ksh 
> 
> sed 's/DATE/"$1"/g' "$2" > "$3"
> exit 0;

I think you are just trying to do a bit too much at once... :)

Try something like:

#!/bin/ksh

read currdate
read infile
read outfile

eval "sed s/DATE/$currdate/g $infile > $outfile"


The input.txt being (note there were two minor typos):

`date +%m-%d-%Y`
FILE.05_24_2001.0529.CSV
/path/to/newfile/FILE.`date +%H.%m_%d_%Y.%H%M`.CSV


The problems with the original script were:

(a) standard input (redirected or not) is not being read
    into the positional parameters $1, $2, etc. -- you need
    'read' for that (with the added benefit that you can
    choose readable variable names ;)

(b) the eval is required to expand the `date ...` commands
    before executing the sed command

BTW, if you need quotes around the s/// (because of whitespace
in the substitution string), you'd have to use double quotes
like "sed \"s///\" ..."  (not 's///'),  or expand the $currdate
before this line, e.g. using

eval "currdate=$currdate"


Happy hacking!

- Almut





More information about the Techtalk mailing list