查找在文本文件中最长的单词 [英] Finding the longest word in a text file

查看:143
本文介绍了查找在文本文件中最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让使用bash发现在文本文件中最大的字和其编号/长度的简单脚本。我知道当我用awk的简单和直接的,但我想尝试用这种方法......可以说,我知道,如果 A = wmememememe ,如果我想找到长度我可以使用回声{#A} 的话,我会回声$ {A} 。但我想这个应用它下面

I am trying to make a a simple script of finding the largest word and its number/length in a text file using bash. I know when I use awk its simple and straight forward but I want to try and use this method...lets say I know if a=wmememememe and if I want to find the length I can use echo {#a} its word I would echo ${a}. But I want to apply it on this below

for i in `cat so.txt` do

在哪里so.txt包含的话,我希望这是有道理的。

Where so.txt contains words, I hope it makes sense.

推荐答案

通常情况下,你要使用而读循环,而不是因为我在$(猫),但因为要被拆分的所有单词,在这种情况下,它会制定出确定。

Normally, you'd want to use a while read loop instead of for i in $(cat), but since you want all the words to be split, in this case it would work out OK.

#!/bin/bash
longest=0
for word in $(<so.txt)
do
    len=${#word}
    if (( len > longest ))
    then
        longest=$len
        longword=$word
    fi
done
printf 'The longest word is %s and its length is %d.\n' "$longword" "$longest"

这篇关于查找在文本文件中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆