Reputation: 18381
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[@]}
Upvotes: 4
Views: 397
Reputation: 47099
Because Perl is fun:
perl -a script.pl <<< 'This is an Example'
T i a E
h s n x
i a
s m
p
l
e
And the script:
@F = map { [/./g] } @F;
while (grep @{$_}, @F) {
printf "%s ", shift @{$_} || ' ' for @F;
print "\n"
}
Alternative script:
perl -pe '$r.=$/while/\S/&&s/(\S)(\S*)|\B/$r.=($1||$").$";$2/ge}{$_=$r' \
<<< 'This is an Example'
T i a E
h s n x
i a
s m
p
l
e
Upvotes: 1
Reputation: 8613
I had created some similar script before. A short but complete POC:
#!/bin/bash
count=0
max=0
#first determine the longest string so we can later pad shorter strings with spaces
for i in $(echo "$1" | xargs -d: -i echo {})
do
size=$(echo $i | wc -c)
if [[ $size > $max ]]
then
max=$size
fi
done
files=""
#then echo the strings vertically inside the tmp files
for i in $(echo "$1" | xargs -d: -i echo {})
do
res=$(echo $i | sed 's/./ &/g' | xargs |tr ' ' '\n' > /tmp/$count.out)
#and add spaces at the end
add_space=$((max-$(echo $i | wc -c)))
for space in $(seq 0 $add_space)
do
echo " " >> /tmp/$count.out
done
files=$files" $count.out"
count=$((count+1))
done
#and finally print them side by side
pr -t -J -m -w 70 -S" " $files
I create tmp files under /tmp, echo the string vertical and later use pr
to print it out.
% ./s.sh "This is an Example"
T i a E
h s n x
i a
s m
p
l
e
Upvotes: 1
Reputation: 8769
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"
}
}
Upvotes: 3
Reputation: 4435
#!/bin/bash
function abc(){
maxIteration=0;
for i in $(seq 1 $#); do
j=$(echo ${!i})
if [ $maxIteration -lt ${#j} ]
then
maxIteration=${#j};
fi
done
COUNTER=0;
while [ $COUNTER -lt $maxIteration ]; do
for i in $(seq 1 $#); do
j=$(echo ${!i})
if [ ${#j} -gt $COUNTER ]
then
echo ${j:$COUNTER:1} | tr '\n' ' ';
else
echo " " | tr '\n' ' ';
fi
done
echo -e "\n"
let COUNTER=COUNTER+1
done
}
abc $@| grep .
Upvotes: 2