procmail
[Top] [All Lists]

Re: Sed question

1999-10-01 13:16:37
Paul asked,

| This is fine, I can increment $count to go get the next line when
| I am ready for it. Trouble is I don't know when file.txt runs out
| of lines. If I have $count set to 50 but there is only 49 lines in
| file.txt, is there an error code I can check so I know I have reached
| the end of file.txt?

You can get the linecount from wc -l, or from

  sed -n \$= file

and save it in a variable.  If you use wc and save it to a variable, make
sure to use this syntax:

 LINES=`wc -l < file`

so that wc will read stdin and not print a filename to stdout; if you do
this instead,

 LINES=`wc -l file`

the name of the file will be included in wc's output and in the variable.

That's as far as I can go without an answer to this question: is this going
on inside a shell script or inside a procmail rcfile?  If it's in a procmail
rcfile, there's a very easy solution:

 :0
 * $ $count^0
 * $ -$LINES^0
 { error routine because $count exceeds $LINES }
 :0E
 { success routine }

In a shell script, you'd need to use the shell's built-in test or /bin/test
to compare the two values.

| While I am here, it seems reading lines from file.txt one at a time
| might generate alot of disk accesses. Is there a way to pull file.txt
| into a variable and have  sed grap lines from the variable, or can
| sed only read files on the disk?

Well, if the file is small enough to fit inside a variable, TEXT=`cat file`;
then you can 

  echo "$TEXT" | sed whatever  # the weak quotes are required

One bit of advice about your sed script: instead of 

  sed -ne ${count}p
or
  sed ${count}!d

which require reading the input all the way to the end every time, do this:

 sed -e ${count}q -ed

which will bail as soon as it has found the right line.  If that's the action
line of a procmail recipe, remember to use the `i' flag.

<Prev in Thread] Current Thread [Next in Thread>