【问题标题】:How to display a word from different lines?如何显示来自不同行的单词?
【发布时间】:2015-02-25 19:04:48
【问题描述】:

我希望能够显示从输入读取的单词的每一行。 现在我可以显示输入读词的索引位置了。

echo "Filename"
read file

echo "A word"
read word

echo $file | awk '{print index($0,"'"$word"'")}'

【问题讨论】:

  • 你为什么不用grep
  • @nu11p01n73R 你能给我举个例子吗,如何使用grep?
  • 根据您的问题grep $word $file 将在$file 中输出包含$word 的行
  • 如果你也想要行号,你可以像这样使用grepgrep -in $word $file
  • 如果您明确您想要的输出是什么,那么我们将能够更好地帮助您。

标签: bash bash4


【解决方案1】:

如果你还想打印行号

read -p 'Filename? ' fname
read -p 'Word to search? ' word
awk /"$word"/'{print NR, $0}' "$fname"

如果你不想要行号

read -p 'Filename? ' fname
read -p 'Word to search? ' word
awk /"$word"/ "$fname"

顺便说一句,每个人都告诉你的是“使用 grep”,但是看看这个

% time for i in {1..10000} ; do grep alias .bashrc > /dev/null ; done

real    0m22.665s
user    0m2.672s
sys     0m3.564s
% time for i in {1..10000} ; do mawk /alias/ .bashrc > /dev/null ; done

real    0m21.951s
user    0m3.412s
sys     0m3.636s

当然gawk 更慢,在本例中为 27.9 秒。

【讨论】:

    【解决方案2】:

    这里的请求是如何使用 grep 的示例。
    以下命令将使用 wget 获取此 stackoverflow 网页的内容,-O - 选项告诉 wget 将 html 输出到 std out,然后通过管道传输到 grep -n grep
    grep 匹配术语“grep”出现在 html 中的实例数,然后输出匹配发生的相应行号 - 并突出显示匹配。

    wget -O - http://stackoverflow.com/questions/27691506/how-to-display-a-word-from-different-lines | grep -n grep
    

    例如当我在终端中运行时(忽略 wget 相关输出)grep -n grepgives:

    42: <span class="comcopy">why dont you use <code>grep</code> ?</span>
    468: <span class="comcopy">@nu11p01n73R Can you give me any example, on how to use grep?</span>
    495: <span class="comcopy">As per your question <code>grep $word $file</code> will output lines in <code>$file</code> containing <code>$word</code></span>
    521: <span class="comcopy">If you want line numbers too, you can use <code>grep</code> like this: <code>grep -in $word $file</code></span>
    

    注意 stackoverflow 语法高亮与您在终端中得到的不同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多