【问题标题】:Find all instances of word occurring in a file查找文件中出现的所有单词实例
【发布时间】:2013-12-12 23:40:06
【问题描述】:

使用 bash 我想知道如何找到以文本开头的单词的所有实例,将其存储为变量并打印出来。

例如,如果这是我的文件

test.conf

$temp_test
test
$1234_$temp
$temp_234

我的输出如下:

   $temp_test
   $temp_234

谁能告诉我这怎么可能?这是迄今为止我能到达的最接近的位置。

while read NAME
do
    echo "$NAME"
done < test.conf

【问题讨论】:

    标签: linux bash shell ubuntu debian


    【解决方案1】:

    你可以使用 grep 和正确的正则表达式:

    grep '^ *$temp' test.conf
    $temp_test
    $temp_234
    

    更新:根据 cmets:

    while read -r l; do
       echo "$l"
    done < <(sed -n '/^ *$temp_/s/^ *\$temp_//p' t.conf)
    
    test
    234
    

    【讨论】:

    • 我确实需要存储变量而不是每次都打印它,因为我想操纵变量。有没有办法做某种循环,我将它添加到一个变量中并回显它?将其存储在变量中将允许我对其进行操作,在我的情况下,获取 $temp_ 之后的内容并将其存储在变量中。
    • 当然你可以像这样循环 grep 的输出:while read -r l; do echo "$l"; done &lt; &lt;(grep '^ *$temp' t.conf)
    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 2012-10-08
    • 2014-08-18
    • 2013-02-11
    • 2014-11-19
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多