我有一个文件,它是这样的:
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 个变量...
谢谢!
最佳答案
让我向您介绍 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
提供变量名,然后打印该行。
找到一些关于您的脚本的评论:
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
就会包含从第二个值开始的值。
关于string - 读取包含字符串的行(Bash),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29796979/