Print the number of characters of every file name using for loop in Mac terminal

Viewed 95

I need to print the number of characters of every file name in a directory using a for loop in the terminal (Mac). This directory is called lorem and it has 3 files: at.txt, lorem.txt and sed.txt.

Up to now I have done this:

lorem sarahr$ ls
at.txt      lorem.txt   sed.txt
FILES=/Users/sarahr/lab-bash-master/lorem/*
lorem sarahr$ for i in $FILES
> do
> echo '$FILES has' | wc -c
> done
      11
      11
      11

Eleven three times is the result, but it's not what I need. Could you help me?

2 Answers

Say you have a directory lorem with the following file structure:

lorem/
├── at.txt
├── lorem.txt
└── sed.txt

The following bash script should work as required when run inside the folder:

for file_name in * ; do echo ${#file_name} ; done

Output:

6
9
7

Documentation for ${#parameter}:

The length in characters of the expanded value of parameter is substituted. If parameter is '*' or '@', the value substituted is the number of positional parameters. If parameter is an array name subscripted by '*' or '@', the value substituted is the number of elements in the array.

First, cd to the directory where your files are located. Change the loop you showed to count the length of the desired file names ($file variable). Use echo -n to suppress the terminal newline, which adds 1 to the file name length.

cd /Users/sarahr/lab-bash-master/lorem
for file in * ; do
    echo -n "$file "
    echo -n "$file" | wc -c
done

Output:

at.txt 6
lorem.txt 9
sed.txt 7
Related