Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Can anyone help me to write a shell script that when given a directory as an argument, finds the longest filename in that directory and any subdirectories?
However my code below does not quite work. It is looking in current directory and sub-directories but when looking for the longest filename is is counting the path to that file aswell.
Is there something I am leaving out of the code?
#!/bin/bash
# Given a directory name as argument
# print the longest filename in that directory.
However my code below does not quite work. It is looking in current directory and sub-directories but when looking for the longest filename is is counting the path to that file aswell.
for file in `find $FILES`; do
len=${#file}
if [ $len -gt $length ]; then
length=$len
filename=$file
fi
done
This is beacuse the find command give the full path of the files it finds. This is the reason why I parsed the output with gawk in the script above.
This echoes the full-path, extract the last field with gawk considering "/" as the field separator (and without the newline control-character, that would give a wrong result) and then count the characters in it.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.