Results 1 to 3 of 3
  1. #1
    Join Date
    May 2004
    Posts
    11

    Unanswered: FInding the longest file name

    Hi

    I need to write a script to run search for the longest filename excluding the file extension through subdirectories given the argument as a dir i.e. "./script dir".

    the problems with the script:

    1. it did not work for searching through subdirectories even for "ls -R"

    2. cannot check files with the white spaces e.g. "my file.txt".

    3. And also, how do i include the absolute path o the file that is found with the longest length e.g.
    the longest filenamed is "\usr\bin\longestfilename".

    many thanks, Daryl


    this is my humble script:

    #1/bin/bash

    maxfile="."

    for file in $(ls -a1R $1)
    do

    file1=${file%.*}
    file1_len=${#file1}

    if test $file1_len -gt ${#maxfile}
    then
    maxfile=$file1

    fi
    done

    echo "The maximum length of the file is ${#maxfile}, Filename: "$maxfile""
    echo "$(ls -R $pwd | grep $maxfile)"

    for file in $(ls -a1R $1)
    do

    file1=${file%.*}
    file1_len=${#file1}



    if test $file1_len -eq ${#maxfile}
    then
    if test $file1 != $maxfile
    then
    echo "The maximum length of the file is ALSO ${#file1}, Filename: "$file""
    echo "$(ls -R $pwd | grep $file)"
    fi


    fi


    done
    Last edited by Daryl Lim; 06-14-04 at 10:47. Reason: error in the scripts

  2. #2
    Join Date
    Jun 2003
    Location
    West Palm Beach, FL
    Posts
    2,713

    Wink

    You could try this:

    Code:
    #!/bin/bash
    dir=$1
    savdir=`pwd`
    cd $dir
    newdir=`pwd`
    maxfile="."
    for file in $(find . -type f)
    do
      file1=${file##*/}
      file2=${file1%.*}
      file1_len=${#file2}
      if test $file1_len -gt ${#maxfile}
      then
        maxfile=$file2
        thefile=$file
      fi
    done
    
    echo "The maximum length of the file is ${#maxfile}, Filename: "$maxfile""
    echo "Full path is: ${newdir}`echo $thefile|cut -c2-`"
    cd $savdir
    The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb

  3. #3
    Join Date
    May 2004
    Posts
    11
    Thanks for the code.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •