gpt4 book ai didi

linux - 如何在linux中用最少的单词输出一个文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:37 25 4
gpt4 key购买 nike

我想编写一个接受一个参数(目录名称)的脚本,该目录包含三个带有随机单词的 .txt 文件。第一个文件包含 1 个单词,第二个文件包含 6 个单词,第三个文件包含 3 个单词。我想显示文件中字数最少的名称和字数。到目前为止我的代码:

#! /bin/bash
if [ $# -gt 0 ]
then
cd $1
number=0
for i in *
do
var=($(wc -w $i))
if [ $var -gt $number ]
then
number=$var
else
wc -w $i
fi
done
else
echo "Please type the name of a directory"
fi

最佳答案

使用 wc 显示单词数,按数字对列表进行排序,然后选择第一个元素。

#!/bin/sh
dir=$1
if [ -d "${dir}" ]; then
wc -w ${dir}/* | sort -n | head -1
else
echo "usage: $0 <directory>" 1>&2
echo " show file in directory with the fewest words" 1>&2
exit 1
fi

正如@Leon 所指出的,只有当${dir} 包含一些 文件(不是空目录)并且它只包含文件(无子目录)。

一个稍微复杂的解决方案是使用find 将检查的路径限制为文件。您还可以使用它遍历子目录:

find "${dir}" -type f -exec wc -w {} + | sort -n | head -1

关于linux - 如何在linux中用最少的单词输出一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40147727/

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