我正在编写一个ksh文件的脚本,希望在其中返回目录中行数最多的文件。该脚本只能使用一个参数,并且必须是有效目录。我发现了2个错误情况,但到目前为止,我遇到的最大行数部分的文件有问题:
#!/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]
从我一直发现的最大行数来看,将来自使用wc,但是由于我还是Shell脚本的新手,因此不确定其格式。任何建议都会有所帮助!
答案 0 :(得分:1)
> for "$1"
> do
> [wc -l | sort -rn | head -2 | tail -1]
for
循环有一个较小的语法错误,并且方括号完全放错了位置。无论如何,您都不需要循环,因为wc
接受文件名参数列表。
wc -l "$1"/* | sort -rn | head -n 1
第一行而不是第二行将包含行数最多的文件。也许您想添加一个选项来修剪数字并仅返回文件名。
如果您要遍历$1
中的文件,看起来就像
for variable in list of items
do
: things with "$variable"
done
其中list of items
可能是通配符表达式"$1"/*
(如上),而do
... done
取代了您想象的正方形括号。
(比较中使用方括号; [ 1 -gt 2 ]
运行[
命令比较两个数字。它可以比较很多不同的东西,例如字符串,文件等。ksh
也有一个更发达的变体[[
,它比传统的[
具有一些功能。)
答案 1 :(得分:0)
我的报价有些生疏,但请尝试使用以下bourne shell脚本:
#!/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