A
AB
ABC
ABCD
ABCDE
read -p "Enter rows:" rows
for((i=1; i<=rows; i ))
do
for((j=1; j<=i; j ))
do
echo -n 'a'
done
echo
done
not able to print the above pattern uses for loop but not getting how to print the abcd pattern.
CodePudding user response:
You could use two printf
s to convert ASCII values to characters:
read -p "Enter rows:" rows
for ((i=1; i<=rows; i )); do
for ((j=1; j<=i; j )); do
printf "\x$(printf %x $((64 j)))"
done
echo
done
If you want to stay with echo -n
you could use an array initialized with all letters and reference it by index:
abc=({A..Z})
read -p "Enter rows:" rows
for ((i=1; i<=rows; i )); do
for ((j=0; j<i; j )); do
echo -n ${abc[j]}
done
echo
done
CodePudding user response:
bash
parameter expansions comprise the ${parameter:offset:length}
substring expansion:
$ str="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
$ read -p "Enter rows:" rows
Enter rows:5
$ for (( i = 1; i <= rows; i )); do echo "${str:0:i}"; done
A
AB
ABC
ABCD
ABCDE
Note: of course if you enter a value greater than 26 the extra output lines will be truncated to 26 characters.
Note: instead of assigning str
manually you can compute it with:
$ arr=({A..Z}); str="${arr[*]}"; str="${str// }"
$ echo "$str"
ABCDEFGHIJKLMNOPQRSTUVWXYZ
This uses brace expansion {A..Z}
to construct the array arr
of uppercase letters, and pattern substitution ${str// }
to remove the intermediate spaces in the expansion of the array ${arr[*]}
. This is handy and less error prone. If you would like to add lower case letters and digits:
$ arr=({A..Z} {a..z} {0..9}); str="${arr[*]}"; str="${str// }"
$ echo "$str"
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
CodePudding user response:
for((i=1; i<=rows; i ))
do
for((j=1; j<=i; j ))
do
printf '%x' $(expr 96 $j) | xxd -p -r
done
echo
done
I've converted ascii 97-->'a' to hex format and than decoded to that char value.
So what is happening here:
printf '%x' $(expr 96 $j)
will print the numbers like
61
6162
616263
61626364
Now we know that \x61
--> 'a'. We want to convert this hex \x61
to a char. So by using -r
we are telling xxd
to convert it from hex to ascii and by using -p
we are telling xxd
that out hex is a continous string not like x61x62x63
but 616263
.
Hope it helps.