gpt4 book ai didi

linux - 计算目录中文件行数的 KSH shell

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:05 24 4
gpt4 key购买 nike

这是提示:

Write a Korn shell script (and show the code for it here) that will determine which file in a directory has the maximum number of lines (this may be different than the file that has the maximum number of bytes). After determining the file with the maximum number of lines, the script will print out the name of the file and the number of lines. The script must only focus on files and ignore subdirectories. The command wc may be helpful. Do not write this script to be executed interactively.

Requirements:

The script must allow either no arguments or 1 argument.

  1. If zero arguments are specified, the script by default will examine the files in the current directory.
  2. If 1 argument is specified, the argument must be the name of a directory. The script will then examine the files in the specified directory.

The script must be able to handle the following error conditions:

  1. More than 1 argument is specified.
  2. The specified argument is not a directory.

The script file name must be: maxlines.sh. The script permissions should be 705.

这是我的代码:

#!/bin/ksh
if [ $# -gt 1];then
echo "There must be 0 or 1 arguments"
exit
fi
if [ -d "$1" ];then
cd $#
fi
max=0
for file in *
do
lines=$(( $( wc -l < "$file" ) ))
if [ $max -lt $lines ];then
max=$lines
fi
done

如有任何建议,我们将不胜感激。我是 Linux 的新手,所以这很令人沮丧。当我运行它时,输出如下所示:

./maxlines.sh[2]: [: ']' missing
./maxlines.sh[9]: cd: 1: [No such file or directory]
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory
wc: standard input: Is a directory

最佳答案

正如@JeremyBrooks 已经解释过的,你的脚本中有很多错误,但你并没有走完全错误的道路。

这是我的修复:

#!/bin/ksh
if [ $# -gt 1 ];then
echo "There must be 0 or 1 arguments"
exit
fi
if [ -d "$1" ]
then
cd $1
fi
max=0
for file in $(find . -name "*" -type f)
do
lines=$(( $( wc -l < "$file" ) ))
if [ $max -lt $lines ];then
max=$lines
maxFile=$file
fi
done
echo "file[$maxFile] - max[$max]"

使用 for file in $(find . -name "*"-type f) 你只会得到文件;在您之前的版本中,您还将获得目录,但您想要计算文件行数。

另一种防止排除目录的方法是for file in $(ls -l * | grep -v "^d"|awk '{print $9}',但这不如查找

当您获得最大行号时,您也忘记了保留文件名,因此在 if 中您必须添加 maxFile=$file

然后不要忘记打印结果:echo "file[$maxFile] - max[$max]" after the for

关于linux - 计算目录中文件行数的 KSH shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com