首页 > 解决方案 > 我如何遍历关键字的出现频率

问题描述

在此处输入图像描述---- 我必须从中搜索关键字的文本文件 [文件名 --- 测试] <cat -Evt ​​文件>

    centos is my bro$
    red hat is my course$
    ubuntu is my OS$
    fqdn is stupid $
    $
    $
    $
    tom outsmart jerry$
    red hat is my boy$
    jerry is samall 

------ 关键字文件是 [word.txt] <cat -Evt ​​文件 >

  red hat$
  we$
  hello$
  bye$
  Compensation

-----我的代码

  while read "p"; do
  paste  -d',' <(echo -n  "$p" ) <(echo "searchall") <(  grep -i "$p" test | wc -l) <(grep  -i -A 1  -B 1   "$p" test )
  done <word.txt
   

----我的期望,输出应该是

 keyword,serchall,frequency,line above it
                            line it find keyword in
                            line below  it
              
 red hat,searchall,2,centos is my bro
                     red hat is my course
                     ubuntu is my OS                                
            
 red hat,searchall,2,tom outsmart jerry
                     red hat is my boy
                     jerry is samall

----但是来自我的代码的输出

  red hat,searchall,2,centos is my bro
  ,,,red hat is my course
  ,,,ubuntu is my OS
  ,,,--
  ,,,tom outsmart jerry
  ,,,red hat is my boy
  ,,,jerry is samall

----请给我建议并指出正确的方向以获得所需的输出。

---- 我正在尝试从文件中 grep 关键字并打印它们这里应该创建两条记录作为关键字(红帽)来两次

----如何循环访问关键字的出现频率。

标签: linuxbashshellloopsgrep

解决方案


这听起来很像家庭作业。
cf BashFAQ以获得更好的阅读体验;保持简单以专注于您的要求。

重写以获得更精确的格式 -

while read key                          # read each search key 
do cnt=$(grep "$key" test|wc -l)        # count the hits
   pad="$key,searchall,$cnt,"           # build the "header" fields
   while read line                      # read the input from grep
   do if [[ "$line" =~ ^-- ]]           # treat hits separately
      then pad="$key,searchall,$cnt,"   # reset the "header"
           echo                         # add the blank line
           continue                     # skip to next line of data
      fi
      echo "$pad$line"                  # echo "header" and data
      pad="${pad//?/ }"                 # convert header to spacving
   done < <( grep -B1 -A1 "$key" test ) # pull hits for this key
   echo                                 # add blank lines between
done < word.txt                         # set stdin for the outer read                       

$: cat word.txt
course
red hat

$: ./tst
course,searchall,1,centos is my bro
                   red hat is my course
                   ubuntu is my OS

red hat,searchall,2,centos is my bro
                    red hat is my course
                    ubuntu is my OS

red hat,searchall,2,tom outsmart jerry
                    red hat is my boy
                    jerry is samall

推荐阅读