Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip multiple strings vertically on bash

I am trying to flip the contents of any sentence vertically. So each chars of any string will get printed vertically in same line. For Example:

Sample Text: This is an Example

Output expected: T i a E
                 h s n x
                 i     a
                 s     m
                       p
                       l 
                       e

In following direction I am trying to achieve this but not able to yet.

    echo "Input provided by user is $@"
    for i in $(seq 1 $#); do

        echo ${!i} | sed 's/./ &/g' | xargs |tr ' ' '\n' 

        done


Current output:

T
h
i
s
i
s
a
n
E
x
a
m
p
l
e

Also, This is also not helping

echo Print text vertically | fold -c -w1
T
h
i
s

i
s

a
n

E
x
a
m
p
l
e

More alternatives which did not worked :

#echo "Input provided by user is $@"

for i in $(seq 1 $#); do

content[i]=$(echo ${!i}|fold -c -w1)

   #echo ${content[i]}


    done

    echo ${content[@]}
like image 291
P.... Avatar asked Mar 13 '23 03:03

P....


1 Answers

max variable holds the max length among all words. For your text it would be: length('Example') which is 7 (maximum out of lengths of all words)

Using an awk script file:

$ awk -f script.awk <<< "This is an Example"
TiaE
hsnx
i  a
s  m
   p
   l
   e

And here is the script:

{
        max=0
        for(i=1;i<=NF;i++)
                max=length($i)>max?length($i):max;

        for(j=1;j<=max;j++)
        {
                for(i=1;i<=NF;i++)
                {
                        temp=substr($i, j, 1);
                        printf temp==""?" ":temp
                }
                printf "\n"
        }
}
like image 74
riteshtch Avatar answered Mar 19 '23 12:03

riteshtch