behzad.nouri
behzad.nouri

Reputation: 78021

Looping through alphabets in Bash

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?

Upvotes: 115

Views: 120420

Answers (8)

hoijui
hoijui

Reputation: 3914

A POSIX compliant version (using AWK):

for letter in $(awk 'BEGIN { for (i=97; i<123; i++) printf("%c ", i) }')
do
    echo $letter
done

Upvotes: 1

Ravikant
Ravikant

Reputation: 11

Looping through alphabet I hope this can help.

for i in {a..z}

for i in {A..Z}

for i in {{a..z},{A..Z}}

use loop according to need.

Upvotes: -4

Alphons
Alphons

Reputation: 323

This question and the answers helped me with my problem, partially.
I needed to loupe over a part of the alphabet in bash.

Although the expansion is strictly textual

I found a solution: and made it even more simple:

START=A
STOP=D
for letter in $(eval echo {$START..$STOP}); do
    echo $letter
done

Which results in:

A
B
C
D

Hope its helpful for someone looking for the same problem i had to solve, and ends up here as well

Upvotes: 5

Thanh Trung
Thanh Trung

Reputation: 3804

With uppercase as well

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

Upvotes: 6

anishsane
anishsane

Reputation: 20980

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}*

Upvotes: 4

LMC
LMC

Reputation: 12877

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.

Upvotes: 29

Kamil Dziedzic
Kamil Dziedzic

Reputation: 5032

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

Upvotes: 187

Mat
Mat

Reputation: 206909

This should get you started:

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

Upvotes: 48

Related Questions