Read line containing String (Bash)

被刻印的时光 ゝ 提交于 2020-02-01 04:55:32

问题


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

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

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

What I have:

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

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

Thanks anyway!


回答1:


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:.

Update

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

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).

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




回答2:


Alternatively, let me present you grep and cut:

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


来源:https://stackoverflow.com/questions/29796979/read-line-containing-string-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!