微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在文本文件中查找最长的单词

我试图做一个简单的脚本find最大的单词和它的数量/长度在文本文件中使用bash。 我知道当我使用awk它的简单而直接,但我想尝试和使用这种方法…让我知道,如果a=wmememememe ,如果我想find长度,我可以使用echo {#a}它的话我会echo ${a} 。 但是我想在下面应用它

for i in `cat so.txt` do

如果so.txt包含文字,我希望它是有道理的。

为什么set -e会导致脚本在遇到以下情况时退出

Bash:从文本文件VAR = VALUE格式中读取variables

在parsinginput参数时很困难

我如何使用sed进行search和replace,而不包括一组字符?

如何通过SFTP将数据传输到远程文件而不将数据存储在Linux Bash的本地文件中?

通常情况下,你想要使用一个while read循环而不是for i in $(cat)中for i in $(cat) ,但是因为你希望所有的单词被分割,所以在这种情况下它可以运行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"

一个班轮。

cat YOUR_FILENAME | sed 's/ /n/g' | sort | uniq | awk '{print length,$0}' | sort -nr | head

打印文件(通过猫)

分词(通过sed)

删除重复项(通过排序| uniq)

在每个单词前加上长度(awk)

按字长对列表进行排序

打印最长的文字

是的,这会比上面的一些解决方案慢,但它也不需要记住bash循环的语义。

longest="" for word in $(cat so.txt); do if [ ${#word} -gt ${#longest} ]; then longest=$word fi done echo $longest

一个方案

for item in $(cat "$infile"); do length[${#item}]=$item # use word length as index done maxword=${length[@]: -1} # select last array element printf "longest word '%s',length %d" ${maxword} ${#maxword}

awk脚本:

#!/usr/bin/awk -f # Initialize two variables BEGIN { maxlength=0; maxword=0 } # Loop through each word on the line { for(i=1;i<=NF;i++) # Assign the maxlength variable if length of word found is greater. Also,assign # the word to maxword variable. if (length($i)>maxlength) { maxlength=length($i); maxword=$i; } } # Print out the maxword and the maxlength END { print maxword,maxlength; }

文本文件

[jaypal:~/Temp] cat textfile AWK utility is a data_extraction and reporting tool that uses a data-driven scripting language consisting of a set of actions to be taken against textual data (either in files or data streams) for the purpose of producing formatted reports. The language used by awk extensively uses the string datatype,associative arrays (that is,arrays indexed by key strings),and regular expressions.

测试:

[jaypal:~/Temp] ./script.awk textfile data_extraction 15

for i in $(cat so.txt); do echo ${#i}; done | paste - so.txt | sort -n | tail -1

因为叉子的数量巨大而慢,但是纯粹的外壳,不需要awk或特殊的bash特性:

$ cat /usr/share/dict/words | xargs -n1 -i sh -c 'echo `echo -n {} | wc -c` {}' | sort -n | tail 23 Pseudolamellibranchiata 23 pseudolamellibranchiate 23 scientificogeographical 23 thymolsulphonephthalein 23 transubstantiationalist 24 formaldehydesulphoxylate 24 pathologicopsychological 24 scientificophilosophical 24 tetraiodophenolphthalein 24 thyroparathyroidectomize

您可以通过向xargs提供-P4来轻松地并行化,例如4个cpu

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐