Reputation: 19
I am scripting a ksh file where I am looking to return the file with the most number of lines in a directory. The script can only take one argument and must be a valid directory. I have the 2 error cases figured out but am having trouble with the files with max lines portion so far I have below:
#!/bin/ksh
#Script name: maxlines.sh
ERROR1="error: can only use 0 or 1 arguments.\nusage: maxlines.sh [directory]"
ERROR2="error: argument must be a directory.\nusage: maxlines.sh [directory]\n"
$1
if [[ $# -gt 1 ]]
then
printf "$ERROR1"
exit 1
fi
if [ ! -d "$1" ]
then
prinf "$ERROR2"
fi
for "$1"
do
[wc -l | sort -rn | head -2 | tail -1]
From what I have been finding the max lines will come from using wc, but am unsure of the formatting as I am still new to shell scripting. Any advice will help!
Upvotes: 0
Views: 64
Reputation: 10003
my quoting is a little rusty, but try this bourne shell script:
#!/bin/sh
#Script name: maxlines.sh
ERROR1="error: can only use 0 or 1 arguments.\nusage: maxlines.sh [directory]"
ERROR2="error: argument must be a directory.\nusage: maxlines.sh [directory]\n"
echo argument 1: "$1"
if [ $# -gt 1 ]
then
echo "$ERROR1"
exit 1
fi
if [ ! -d "$1" ]
then
echo "$ERROR2"
exit 1
fi
rm temp.txt
#echo "$1"/*
for i in "$1"/*
do
if [ -f "$i" ]
then
#echo 2: $i
wc -l "$i" >> temp.txt
#else echo $1 is not a file!
fi
done
cat temp.txt | sort -rn | head -1
Upvotes: 0
Reputation: 189628
> for "$1"
> do
> [wc -l | sort -rn | head -2 | tail -1]
The for
loop has a minor syntax error, and the square brackets are completely misplaced. You don't need a loop anyway, because wc
accepts a list of file name arguments.
wc -l "$1"/* | sort -rn | head -n 1
The top line, not the second line, will contain the file with the largest number of lines. Perhaps you'd like to add an option to trim off the number and return just the file name.
If you wanted to loop over the files in $1
, that would look like
for variable in list of items
do
: things with "$variable"
done
where list of items
could be the wildcard expression "$1"/*
(as above}, and the do
... done
take the place where you imagine you'd want square brackets.
(Square brackets are used in comparisons; [ 1 -gt 2 ]
runs the [
command to compare two numbers. It can compare a lot of different things -- strings, files, etc. ksh
also has a more developed variant [[
which has some features over the traditional [
.)
Upvotes: 1