I would be grateful if someone could help me. I am trying to write a .sh script in UNIX.
I have the following code;
User[0]=john
User[1]=james
User[2]=ian
User[3]=martin
for x in ${User[@]}
do
print ${#x}
done
This produces the following output;
4
5
3
6
What I would like to do is only print the longest length of string, in this case '6'. (I will also be storing the single result in a variable for later use). I have experimented with awk & gawk etc and I'm really struggling. The above code is a very simple breakdown of a more complicated problem, but if someone could solve the above it would make a big difference.
Appologies if this is very straight forward, quite new to this.
Regards
---------- Post updated at 05:11 PM ---------- Previous update was at 05:02 PM ----------
I should of added that i need to keep the for loop, hopefully there is a way of doing it within this kind of loop.
I would like to make an addition to the above. I have the following;
#!/bin/sh
theUse[0]=john
theUse[1]=james
theUse[2]=ian
theUse[3]=martin
m=-1
for x in ${theUse[@]}
do
if [ ${#x} -gt $m ]
then
m=${#x}
fi
done
printf "%0s %-$m %0s\n" random text $m random text
The difference with the above (addition of the last line) is that I'm trying to use the variable $m (which stores the length of the longest string) and use it as a parameter within the printf padding.
I've tried many different ways but it doesnt seem to work. Any ideas?
With a gap of 6 spaces between the last two strings (6 being the length of the longest username 'martin')
hope that makes sense.
Regards
---------- Post updated at 05:12 PM ---------- Previous update was at 05:10 PM ----------
when submitting the last post the all the random text strings were aligned together. I basically need a gap of 6 spaces between the last two strings. sorry
I typed the code as you wrote it, however when run it doesn't output anything. I would also prefer not to state an actual number in the code, rather just use the scalar variable.