Tips and Tricks About Computers, Web Development, Linux, the Internet and the Like
Generating sequences of numbers or characters with bash
If you ever needed to generate a sequence of characters or numbers, the terminal (using bash) is a quick and easy way to do it. Lets explore some examples bash’s brace expansion:
$ echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y zby defining a start and end character with the ‘..’ in between, we tell bash to fill in the rest and echo a list for us. Those are all lowercase, what if you wanted uppercase? simple:
$ echo {A..Z}
A B C D E F G H I J K L M N O P Q R S T U V W X Y ZOr both, with a few extra characters in the mix:
$ echo {A..z}
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y zIt doesn’t always have to be a-z though,
$ echo {A..G}
A B C D E F GThis also works with numbers:
$ echo {0..9}
0 1 2 3 4 5 6 7 8 9
echo {0..100}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100Descending as well as ascending
$ echo {9..0}
9 8 7 6 5 4 3 2 1 0There is another method to generate a sequence of numbers from the command line, rightfully called ‘seq’
$ seq 1 5 1 2 3 4 5
The difference here is that it’s delimited by a new line, however, we can override that with the -s (seperator) flag
$ seq -s " " 1 10 1 2 3 4 5 6 7 8 9 10
| Print article | This entry was posted by Tyler Mulligan on August 15, 2009 at 10:14 am, and is filed under Bash, Computers, Linux, Software, Ubuntu. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 2 years ago
Please note that this is bash3 only and not for bash2. I used a hosting provider that had a bash2 binary and was _very_ confused as to why my scripts were broken.
But thanks for the tips!
about 1 year ago
I need numbers in words format