tags:

views:

2554

answers:

2

I need to have a script read the files coming in and check information for verification.

On the first line of the files to be read is a date but in numeric form. eg: 20080923 But before the date is other information, I need to read it from position 27. Meaning line 1 position 27, I need to get that number and see if it’s greater then another number.

I use the grep command to check other information but I use special characters to search, in this case the information before the date is always different, so I can’t use a character to search on. It has to be done by line 1 position 27.

Thanks.

+3  A: 
sed 1q $file | cut -c27-34

The sed command reads the first line of the file and the cut command chops out characters 27-34 of the one line, which is where you said the date is.

Added later:

For the more general case - where you need to read line 24, for example, instead of the first line, you need a slightly more complex sed command:

sed -n -e 24p -e 24q | cut -c27-34
sed -n '24p;24q' | cut -c27-34

The -n option means 'do not print lines by default'; the 24p means print line 24; the 24q means quit after processing line 24. You could leave that out, in which case sed would continue processing the input, effectively ignoring it.

Finally, especially if you are going to validate the date, you might want to use Perl for the whole job (or Python, or Ruby, or Tcl, or any scripting language of your choice).

Jonathan Leffler
I should probably have added - alternatively, use Perl and do the date validation in the same script that chops the data up. Python could also be used for that, too. You could also do it all in a single sed command: sed -n -e '1s/^.\{26\}\(........\).*/\1/p' $fileHowever, sed | cut is easy.
Jonathan Leffler
+1  A: 

You can extract the characters starting at position 27 of line 1 like so:

datestring=`head -1 $file | cut -c27-`

You'd perform your next processing step on $datestring.

DGentry