so I am just learning bash and right now I am trying to write one line codes to solve some problems. So write now I am listing all the users in stampede and trying to get the length and name of the longest string. So this is where I am at
getent passwd | cut -f 1 -d: | wc -L
getent passwd - (too get the userid list), the cut command to get the first userid and then wc -L to get the longest length. Now I am trying to figure out how do I echo that? So any input on that would be awesome thank you!
To get the name of the user with the longest name, use:
getent passwd | awk -F: '{longest=length($1)>length(longest)?$1:longest} END{print longest}'
-F:
Tell awk to use a colon as the field separator.
longest=length($1)>length(longest)?$1:longest
For every line of input, this statement is executed. It assigns to the variable longest the result of a ternary statement:
length($1)>length(longest)?$1:longest
This statement tests the condition length($1)>length(longest). Here, length($1) is the length of the name of the current user and length(longest) is the length of the longest name seen previously. If the current name is longer, the ternary expression returns the current name, $1. Otherwise, it returns the previous longest name, longest.
END{print longest}
After we have finished reading the file, this prints the name that was the longest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With