Search code examples
stringbashif-statementstring-lengthwc

error when using wc -c with file names


I am running this code, that sorts files in the desired folders. If a file name has 13 chars it should run the first statement, else the second.

for i in *.png; do if [ "$($i | wc -c)" -eq 13 ]; then
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:3}.jpg
else
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:4}.jpg
fi;
done

the problem is, that [ "$($i | wc -c)" -eq 13 ] is always 0, but clearly, file names have some length. What is the correct way of evaluating wc -c in an if statement?


Solution

  • Replace

    [ "$($i | wc -c)" -eq 13 ]
    

    by

    [ $(printf "%s" "$i" | wc -c) -eq 13 ]
    

    or use

    [ ${#i} -eq 13 ]