【问题标题】:Read line containing String (Bash)读取包含字符串 (Bash) 的行
【发布时间】:2015-06-30 01:50:01
【问题描述】:

我有一个文件,它是这样的:

Device: name1
random text
Device: name2
random text
Device: name3
random text

我有一个变量:MainComputer

我想得到什么(对于每个名字,我有 40 个名字):

   MainComputer -> name1
   MainComputer -> name2
   MainComputer -> name3

我有什么:

var="MainComputer"   
var1=$(awk '/Device/ {print $3}' file)
echo "$var -> $var1"

这仅给出箭头“->”和第一个变量的链接,我希望它们用于其他 40 个变量...

还是谢谢!

【问题讨论】:

    标签: string bash file variables contain


    【解决方案1】:

    让我介绍你awk:

    $ awk '/Device/ {print $2}' file
    name1
    name2
    name3
    

    这会在包含Device 的行上打印第二个字段。如果要检查它们是否以 Device 开头,可以使用^Device:。

    更新

    要获得您在已编辑问题中提到的输出,请使用以下命令:

    $ awk -v var="MainComputer" '/Device/ {print var, "->", $2}' a
    MainComputer -> name1
    MainComputer -> name2
    MainComputer -> name3
    

    它通过-v提供变量名,然后打印该行。


    找到一些关于你的脚本的 cmets:

    file="/scripts/file.txt"
    while read -r line
    do
         if [$variable="Device"]; then # where does $variable come from? also, if condition needs tuning
         device='echo "$line"' #to run a command you need `var=$(command)`
    echo $device #this should be enough
    fi
    done <file.txt #why file.txt if you already stored it in $file?
    

    检查bash string equality 以了解[[ "$variable" = "Device" ]] 的语法应该如何(或类似)。

    另外,您可以说while read -r name value,这样$value 将包含从第二个值开始的值。

    【讨论】:

    • 对不起,忘了这个:variable="Device" file="/scripts/file.txt" while read -r line do if [$variable="Device"];然后 device='echo "$line"' echo $device fi done
    • fedorqui,这行得通,你!但是现在当我有输出时,我如何将它们放入变量中?
    • @Omnomnom 只需说var=$(command)。或者,在这种情况下,var=$(awk '/Device/ {print $2}' file)。
    • @Omnomnom 您刚刚更新了您的问题,但您所说的与您在此处的评论完全不同。请试着澄清一下
    • 我明天要试试这个,但我认为它会起作用,谢谢!
    【解决方案2】:

    或者,让我介绍一下 grep 和 cut:

    $ grep "^Device:" $file | cut "-d " -f2-
    

    【讨论】:

    • 我猜cut "-d " -f2- 是一个错字。你可能想说cut -d" "
    • @fedorqui:它们有何不同?两者都将得到与cut 相同的参数值。 -d" " 对我来说更具可读性。但从bash 的角度来看,两者是相同的。 (cygwin 的 cut.exe 可能不是这种情况,如果从 cmd 运行。cmd 将 " 传递给子进程。)
    • 没错,你可以选择你最喜欢的版本。
    • @fedorqui:是的,"-d " 是不寻常的,但是,正如@anishsane 指出的那样,-d" " 在cut 看到时会产生完全相同的字符串它:在 shell 执行 quote remove 之后,两种形式都会产生一个包含 d 后跟空格的参数。
    • @mklement0 太棒了,不知道。为了让它“持久”,我只是将它作为答案发布在use space as a delimiter with cut command。
    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 2019-06-03
    • 1970-01-01
    • 2012-03-10
    • 2014-12-07
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多