【问题标题】:How to print n number of characters appearing after a searched character in BASH?如何打印在 BASH 中搜索到的字符后出现的 n 个字符?
【发布时间】:2023-03-16 18:27:01
【问题描述】:

我有一个这样的文本文件:

Once upon a time, there lived a rabbit who lived in the forest.
One day, rabbit found bear.
Bear said, "Hello!"

给定一个字母,例如“e”,我需要输出对e + the next 2 characters的所有搜索,例如,这将打印以下内容:

e u
e, 
ere
e l
ed 
ed 
est
e d
ear
ear
ell
  • 可以打印任何字符,包括标点或符号,但不能打印换行符。
  • 这是区分大小写的。如果搜索“e”,则不会搜索“E”。

每次搜索到的字符出现在 BASH 的文件中时,如何打印搜索到的字符以及接下来的 2 个字符?

【问题讨论】:

    标签: bash grep


    【解决方案1】:

    你能用perl吗?

    perl -lne 'print "e",$_ for $_ =~ /(?<=e)(..)/g' file
    

    $ perl -lne 'print "e",$_ for $_ =~ /(?<=e)(..)/g' file
    e u
    e, 
    ere
    e l
    ed 
    ed 
    e f
    est
    e d
    ear
    ear
    ell
    

    【讨论】:

      【解决方案2】:

      要包含重叠的字符串,你可以使用这个:

      while IFS= read -r line
      do
          while [ "${#line}" -gt 2 ]
          do
              if [ "${line:0:1}" = 'e' ]
              then
                  echo "${line:0:3}"
              fi
              line="${line:1}"
          done
      done
      

      【讨论】:

        【解决方案3】:

        如果你的 grep 支持 -o,那就简单了

        grep -o e..
        

        【讨论】:

        • 这不会像 l0b0 所说的那样包含重叠字符串
        【解决方案4】:

        艰难的路

        echo $(cat file.txt ) > temp
        grep -o . temp | nl | grep e | cut -f1 | xargs -i -n1 echo "{}; {} + 2;" | bc | xargs -n2 echo | sed 's/ /-/' |  xargs -i{} -n 1 cut -c {} temp
        

        【讨论】:

        • echo $(cat file.txt ) &gt; temp:请认真一点。
        猜你喜欢
        • 2022-12-24
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        • 2013-05-13
        • 1970-01-01
        • 2018-03-16
        • 1970-01-01
        • 2021-12-21
        相关资源
        最近更新 更多