0
votes

I need to write a bash script that copies the files to dir2 that match the character count in their filename with a given int value given as an argument to the script. I've tried to do something but I cannot manage to get the files copied at all.

read number

list=`for file in *; do echo  -n "$file" | wc -m; done`

for file in $list

do

if [ $file -eq $number ]

then

cp file dir2

fi

done
1
Do the filenames contain extensions and do they count towards the character count? - Jonathan
No, the extensions do not need to go towards the char count - David Trpcevski

1 Answers

1
votes

In your code, list is a list of filename lengths, not filenames. So $file is just a number. You also missed the leading $ on $file.

You don't need t use the wc program, you can get the length of a variable name using ${#name}. I think you need something like this:

while [[ $number != +([0-9]) ]]
do
    read -p "Enter number: " number
done

for file in *
do

    if (( ${#file} == $number ))
    then
        cp "$file" dir2
    fi

done