Read line containing String (Bash)

房东的猫 提交于 2019-12-04 11:08:38
fedorqui

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.

Alternatively, let me present you grep and cut:

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