读取包含字符串的行(Bash)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29796979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:51:01  来源:igfitidea点击:

Read line containing String (Bash)

stringbashfilevariablescontain

提问by Omnomnom

I have a file, and its something like this:

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

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

I have a variable: MainComputer

我有一个变量:MainComputer

What I want to get (for each name, i have like 40 names):

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

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

What I have:

我拥有的:

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

This only gives the arrow "->" and the link for the first variable, I want them for the other 40 variables...

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

Thanks anyway!

不管怎么说,还是要谢谢你!

回答by fedorqui 'SO stop harming'

Let me present you awk:

让我向您介绍awk

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

This prints the second field on the lines containing Device. If you want to check that they start with Device, you can use ^Device:.

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

Update

更新

To get the output you mention in your edited question, use this:

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

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

It provides the variable name through -vand then prints the line.

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



Find some comments regarding your script:

查找有关您的脚本的一些评论:

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?

Check bash string equalityto see how [[ "$variable" = "Device" ]]should be the syntax (or similar).

检查bash 字符串相等性以查看[[ "$variable" = "Device" ]]语法(或类似语法)应该如何。

Also, you could say while read -r name value, so that $valuewould contain from the 2nd value on.

此外,您可以说while read -r name value, 以便$value从第二个值开始包含。

回答by Daniel Stenberg

Alternatively, let me present you grep and cut:

或者,让我向您展示 grep 和 cut:

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