Looping through alphabets in Bash

93,969

Solution 1

for x in {a..z}
do
    echo "$x"
    mkdir -p path2/${x}
    mv path1/${x}*.ext path2/${x}
done

Solution 2

This should get you started:

for letter in {a..z} ; do
  echo $letter
done

Solution 3

here's how to generate the Spanish alphabet using nested brace expansion

for l in {{a..n},ñ,{o..z}}; do echo $l ; done | nl
1  a
 ...
14  n
15  ñ
16  o
...
27  z

Or simply

echo -e {{a..n},ñ,{o..z}}"\n" | nl

If you want to generate the obsolete 29 characters Spanish alphabet

echo -e {{a..c},ch,{d..l},ll,{m,n},ñ,{o..z}}"\n" | nl

Similar could be done for French alphabet or German alphabet.

Solution 4

Using rename:

mkdir -p path2/{a..z}
rename 's|path1/([a-z])(.*)|path2/$1/$1$2' path1/{a..z}*

If you want to strip-off the leading [a-z] character from filename, the updated perlexpr would be:

rename 's|path1/([a-z])(.*)|path2/$1/$2' path1/{a..z}*

Solution 5

With uppercase as well

for letter in {{a..z},{A..Z}}; do
  echo $letter
done
Share:
93,969
behzad.nouri
Author by

behzad.nouri

Updated on November 19, 2021

Comments

  • behzad.nouri
    behzad.nouri over 2 years

    I want to mv all the files starting with 'x' to directory 'x'; something like:

    mv path1/x*.ext path2/x
    

    and do it for all alphabet letters a, ..., z

    How can I write a bash script which makes 'x' loops through the alphabet?

  • Admin
    Admin almost 6 years
    May I ask why you enclose x with braces on 4th and 5th line?
  • Kamil Dziedzic
    Kamil Dziedzic over 5 years
    It's not required here but well, it works, and makes parameters stand out better;) gnu.org/software/bash/manual/…
  • Weijun Zhou
    Weijun Zhou over 5 years
    Usually "$x" is enough and a better way to make it stand out.
  • Enrico Carlesso
    Enrico Carlesso about 3 years
    Ugly alternative to avoid splitting the alphabet: for j in $(for i in $(echo {a..z} ñ ch ll ); do echo $i; done| sort | xargs); do echo "Hello-$j"; done
  • 4dc0
    4dc0 about 3 years
    @WeijunZhou that is a problem if you want to expand variable x followed by the letters 'y' and 'z'. if you try to expand "$xyz" the interpreter will think you're trying to print a variable named xyz while "${x}yz" will let the interpreter know exactly what you're trying to do
  • Weijun Zhou
    Weijun Zhou about 3 years
    I meant "$x"yz.
  • Robert
    Robert over 2 years
    That is already covered in other answers. Please don't add duplicates, or explain how yours is better than the previous answers.