linux - 词频和-gt

标签 linux bash shell awk sed

我的代码检查文件中所有单词的频率并显示,但我想知道如何只显示长度大于变量 k 的单词。 这是我的代码:

#!/bin/bash
if [ $# -eq 0 ]; then

    echo "you need an argument"
    exit 2
fi

echo "Insert k"
read k
for file in $@; do
    if ! [ -f $file ]; then
    echo "Not a file"
    exit 2
    fi
    sed -e 's/\s/\n/g' < $file | sort | uniq -c | sort -nr
done

文件内容:

ceva
ceva
aiurea
sebi
este
cel
mai
smecher

输出:

     2 ceva
     1 smecher
     1 sebi
     1 mai
     1 este
     1 cel
     1 aiurea

最佳答案

使用 awk 计算字长大于变量的频率:

awk -v k=3 'length() > k { freq[$0]++} END{for (i in freq) print freq[i], i}' file |
sort -rn

2 ceva
1 smecher
1 sebi
1 este
1 aiurea

完整脚本:

#!/usr/bin/env bash
if [[ $# -eq 0 ]]; then
    echo "you need an argument"
    exit 2
fi

read -p "Insert k: " k

for file in "$@"; do
    if [[ ! -f $file ]]; then
       echo "$file is not a file"
       exit 2
    fi

    echo "$file:"
    awk -v k=$k 'length()>k{freq[$0]++} END{for (i in freq) print freq[i], i}' "$file" | sort -rn
done

关于linux - 词频和-gt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481413/

相关文章:

linux - Windows CMD命令对应linux命令

linux - 在 Linux 中以特定时间间隔调用函数

linux - 命令替换如何工作

linux - Rust:如何生成在父级收到SIGINT/SIGTERM之后仍继续存在的子进程

bash - 将带有后缀的 date() 添加到 sqlite3 查询中

linux - 检测 unix 中的目录更改

linux - abas-ERP : Excecute a FO-Service-Program from a cronjob

linux - 当我 sudo bash -c 时会发生什么?

linux - 关于 Linux 中的线程

linux - 从主 bash 脚本启动另一个 bash 脚本