i want the longest word from the file using sed.
can any one help me in this case?
Sure it can be done a lot simpler....
awk ' BEGIN {
X=0
}
{
n = 1
while ( n <= NF ) {
Y = length($n)
if ( Y > X ) {
X = Y
WORD = $n
}
n++
}
}
END {
print WORD
} ' file
awk '{ if ( length >a ) { a = length; b=$0 }}END{ print b }' filename
matrixmadhan - this will print the lonest line rather than the longest word though won't it?
Hi.
What is your definition of a word?
Why is the solution required to be with sed?
What have you tried so far?
cheers, drl
Or something like this with zsh/bash:
read< <(sort -rn <(for w in $(<file);do w="${w//[,.:\"\'()<>]}"
printf "%d %s\n" "${#w}" "$w";done));printf "%s\n" "${REPLY#* }"
For example:
bash 3.2.25(1)$ cat file
The Z shell (zsh) is a Unix shell that can be used as an interactive login shell
and as a powerful command interpreter for shell scripting. Zsh can be thought of
as an extended bourne shell with a large number of improvements, including some
of the most useful features of bash, ksh, and tcsh.
bash 3.2.25(1)$ read< <(sort -rn <(for w in $(<file);do w="${w//[,.:\"\'()<>]}"
printf "%d %s\n" "${#w}" "$w";done));printf "%s\n" "${REPLY#* }"
improvements
awk 'BEGIN{ l=0}
{
for ( i=1 ;i<=NF;i++){
gsub(/[[:punct:]]/,"",$i)
if (length($i) >l ) {
l=length($i)
f=$i
}
}
}
END{
print l, f
}' "file"
output:
# ./test.sh
12 improvements