[英]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 $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字符串相等性 ,看看[[ "$variable" = "Device" ]]
應該是語法(或類似)。
此外,您可以說while read -r name value
,以便$value
包含第二個值。
或者,讓我告訴你grep和cut:
$ grep "^Device:" $file | cut "-d " -f2-
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.