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!
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:
.
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-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With