读取包含字符串 (Bash) 的行
Read line containing String (Bash)
我有一个文件,它是这样的:
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 }' file)
echo "$var -> $var1"
这只为第一个变量提供了箭头“->”和 link,我希望它们用于其他 40 个变量...
谢谢!
让我来介绍你 awk
:
$ awk '/Device/ {print }' file
name1
name2
name3
这将在包含 Device
的行上打印第二个字段。如果要检查它们是否以 Device 开头,可以使用 ^Device:
.
更新
要获得您在编辑的问题中提到的输出,请使用:
$ awk -v var="MainComputer" '/Device/ {print var, "->", }' 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
将包含从第二个值开始的值。
或者,让我向您展示 grep 和 cut:
$ grep "^Device:" $file | cut "-d " -f2-
我有一个文件,它是这样的:
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 }' file)
echo "$var -> $var1"
这只为第一个变量提供了箭头“->”和 link,我希望它们用于其他 40 个变量...
谢谢!
让我来介绍你 awk
:
$ awk '/Device/ {print }' file
name1
name2
name3
这将在包含 Device
的行上打印第二个字段。如果要检查它们是否以 Device 开头,可以使用 ^Device:
.
更新
要获得您在编辑的问题中提到的输出,请使用:
$ awk -v var="MainComputer" '/Device/ {print var, "->", }' 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
将包含从第二个值开始的值。
或者,让我向您展示 grep 和 cut:
$ grep "^Device:" $file | cut "-d " -f2-