2

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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
sanjihan
  • 5,592
  • 11
  • 54
  • 119

2 Answers2

3

Replace

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

by

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

or use

[ ${#i} -eq 13 ]
Cyrus
  • 84,225
  • 14
  • 89
  • 153
2

Use bash string utilities to get the string length. You don't need wc at all. And double-quote all variables in script to avoid word-splitting done by the shell.

for i in *.png; do 
    if ((${#i} == 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
Inian
  • 80,270
  • 14
  • 142
  • 161