Thursday, October 25, 2007

Cherry Picking - Listing Out File Date/Size Information with Ksh

Here we go,

This is a quick way to list out file date/size info from a list of files.

For instance, if you have the following in a file (your list of files you want to watch - for our purposes, they'll be in the same directory as the script)

100 HE01 file1.txt check_it
200 LTXS file2.txt out


The first two fields don't matter and neither does the last. We just put them in there so that this example would be able to illustrate picking out fields that we care about (just the filenames - file1.txt, etc)

This script right here will read that file (called input.txt) and print out the following information:

file1.txt 3 Oct_25_22:27
file2.txt 12 Oct_25_22:27


And here it is:


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/ksh

#
# 2007 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

cat input.txt|while read v w x y
do
if [ -e $x ]
then
num_lines=`wc -l $x|sed -e 's/ *//' -e 's/ .*$//'`
time_stamp=`ls -l $x|awk '{print $6 "_" $7 "_" $8}'`
echo "$x $num_lines $time_stamp"
fi
done


Simple enough. Notice on the first line that we use "while read" and then list out 4 variables. Basically "while read" variables are consumptive. That is if we just said "while read x" it would assign the entire line of that file to the variable x. Here we only wanted the third field on the line.

The variables v and w are important because they set the stage for letting x become the file name in the script. y takes up the whole rest of the line, also ensuring that x is just the 3rd field (the text name that we want to work on).

All the sed and awk for later. Hopefully this little bit of script will prove useful to you at some point in your trials :)

, Mike