使用 ksh return 目录中行数最多的文件

Using ksh to return the file with the most lines in a directory

我正在编写一个 ksh 文件的脚本,我正在寻找 return 目录中行数最多的文件。该脚本只能接受一个参数,并且必须是一个有效的目录。我已经弄清楚了 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"

if [[ $# -gt 1 ]]
        then
                printf "$ERROR1"
                exit 1
fi
if [ ! -d "" ]
        then
        prinf "$ERROR2"
fi
for ""
do
    [wc -l | sort -rn | head -2 | tail -1]

根据我的发现,最大行数将来自使用 wc,但不确定格式,因为我对 shell 脚本编写还是陌生的。任何建议都会有所帮助!

我的引用有点生疏,但试试这个 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: ""
if [ $# -gt 1 ]
        then
        echo "$ERROR1"
    exit 1
fi
if [ ! -d "" ]
        then
        echo "$ERROR2"
    exit 1
fi
rm temp.txt
#echo ""/*
for i in ""/*
    do
    if [ -f "$i" ] 
        then
            #echo 2: $i
            wc -l "$i" >> temp.txt
        #else echo  is not a file!
    fi
    done
cat temp.txt | sort -rn | head -1
> for ""
> do
>    [wc -l | sort -rn | head -2 | tail -1]

for循环有一个小的语法错误,方括号完全错位了。无论如何你都不需要循环,因为 wc 接受文件名参数列表。

wc -l ""/* | sort -rn | head -n 1

第一行,而不是第二行,将包含行数最多的文件。也许您想添加一个选项 trim 关闭数字和 return 只是文件名。

如果你想遍历 </code> 中的文件,那看起来像 </p> <pre><code>for variable in list of items do : things with "$variable" done

其中 list of items 可以是通配符表达式 ""/*(如上},do ... done 位于您想象的位置想要方括号。

(方括号用于比较;[ 1 -gt 2 ]运行[命令来比较两个数字。它可以比较很多不同的东西——字符串、文件等。ksh 还有一个更发达的变体 [[,它比传统的 [ 有一些特点。)