包含字符串读线(击) [英] Read line containing String (Bash)

查看:139
本文介绍了包含字符串读线(击)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file, and its something like this:

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

我有一个变量:MainComputer

I have a variable: MainComputer

我想获得(每个名字,我有一个像40名)什么:

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

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

我有什么:

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

这不仅赋予了箭头 - >和链接的第一个变量,我希望他们为其他40个变量...

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

不管怎样,谢谢!

推荐答案

让我present您 AWK

Let me present you awk:

$ awk '/Device/ {print $2}' 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:.

为了让你在编辑的问题提的输出,使用:

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

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

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

It provides the variable name through -v and then prints the line.

找到有关你的脚本一些评论:

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 equality to see how [[ "$variable" = "Device" ]] should be the syntax (or similar).

另外,你可以说同时读取-r名称值,使 $值将从第二包含价值上。

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

这篇关于包含字符串读线(击)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆