请帮助编写查找具有最长文件名的文件的脚本

请帮助编写查找具有最长文件名的文件的脚本

我正在尝试创建一个循环遍历整个文件目录的脚本,以便找到该目录中字符最多的文件。附件是我的代码示例。我究竟做错了什么?

  1 #!/bin/bash
  2 #This program takes an array of files and sees which is the largest in a directory
  3 
  4 files=() #create an Empty array for which files will be stored
  5 longest=${files[0]} #Sets point of origin for the current largest file at 0
  6 
  7 echo "Enter Directory name:"
  8 read dir_name
  9 
 10 if [ -d "$dir_name" ]; then #Test file to see if it's a directory
 11 
 12         for i in "$dir_name"/* #For loop to discern the file with the most characters
 13            do
 14                 files=$dir_name
 15                 if [ "${#i}" -gt "${#longest}" ]; then
 16                         longest="$i"
 17                         echo "$i && Character count:${#files[i]}"
 18                 fi
 19            done
 20 
 21 elif [ ! -d "$dir_name" ]
 22 then
 23         echo "Sorry not the directory we are looking for"
 24         exit 0
 25 fi
 26 
 27 

答案1

我在您的代码中看到几个错误:

  1. 在你的循环中,开头和结尾都for没有 a 。dodone
  2. 如果您写if [ ... ] then在一行中,则需要;then.
  3. 您不需要为了脚本的目的将文件存储在数组中,您可以直接迭代目录中的文件

更新:我重写了脚本来执行您想要的操作:获取目录中最长文件名的文件并使用其字符数打印它:

#!/bin/bash

longest=0

if [ $# -lt 1 ]; then # if no argument given, read the directory from input
    echo -n "Enter directory name: "
    read dir_name
else
    dir_name=$1 # this allows execute the script with the directory as argument
fi

if [ -d "$dir_name" ]; then # process if what was given is a directory
    for file in "$dir_name"/* ; do
        if [ -f "$file" ]; then # do it only for files
            filename=$(basename $file) # get only the filename: NOT in all UNIX
            if [ ${#filename} -gt $longest ]; then
                longest=${#filename} # store new longest
                longest_file=$file # save the file
            fi
        fi
    done
    # we are done, print results
    echo -n "The file with longest filename is" $longest_file
    echo " with a filename" $longest "characters long"
fi

测试:

给定一个目录“test”,其中包含以下常规文件:

a ab abc abcd

该脚本的输出如下所示:

The file with longest filename is test/abcd with a filename 4 characters long

相关内容