Assume I have a text file as below
abcd
aaaaaaa
gfgk
hahahahahahhahh
gf
Then gf would be returned.Any good ideas?
|
feedback
|
|
Assuming your lines each contain a 'word' of characters,
# Let your text be in `str.txt`
awk '{print length($1), $1}' str.txt | sort -nk 1 | head -1
# Output: 2 gf ## Which is the shortest string
You can optimize this to avoid a sort with some more AWK. Also note that if you have multiple shortest strings, this will give you one of them. | |||||||
feedback
|
|
Awk is great for this:
The first part sets the "shortest" variable to the current line if it is the first line or if the length is shorter than the shortest line seen previously. Finally, the last part prints out the value of shortest. | |||
|
feedback
|
|
BASH FAQ entry #1 tells how to read a file line by line. | |||
|
feedback
|
|
A solution using sed, and keeping the 1st shortest line from the file:
To keep the last shortest line from the file:
Bellow is an explained version of the 1st shortest line in the form of a sed script file that can be run using
| |||
|
feedback
|