I have a file with under 200 entries, they are not really uniform but with a grep before and after command I can get client data. Here is what the output of the command
grep -i -b -A4 " Type : Client" sample.txt
Index : 11
Type : Client, Disk Proxy Client
Location : 192.1680.11
Up Time : 0d 0h 25m
Revision : 6.3.1
Index : 12
Type : Client
Location : 192.1680.12
Up Time : 0d 0h 25m
Revision : 7.0.1
Index : 56
Type : Client
Location : 10.0.10.112
Up Time : 0d 0h 25m
Revision : 5.3.1
I want to run a while/for loop and separate each line into a variable to then push these values to database.
As a sample of getting I can get the "Location" for each grep result I can use this. I would like to put this in a script and grab all the output in to individual variables.
cat sample.txt |grep -i -b -A4 "Type" |while read client; do echo "$client" |grep Location |awk '{print $4}'; done
192.168.0.11
192.168.0.12
10.0.10.112
But if I try to put the same command into a multi-line script it gets processed as individual lines.
I would like to do more grep/sed..etc to get
index=11
type=client
location=192.168.0.11
fake sql query
sql -update .... $index,$type,$location
CodePudding user response:
It seems like this might be what you're trying to do:
$ cat tst.sh
#!/usr/bin/env bash
while IFS= read -r rec; do
echo sql -update .... "$rec"
done < <(
awk '
BEGIN {
FS = "[[:space:]]*:[[:space:]]*"
OFS = ","
}
$1 ~ /^(Index|Type|Location)/ {
rec = rec sep $2
sep = OFS
}
!NF {
print rec
rec = sep = ""
}
END {
print rec
}
' "${@:--}"
)
$ ./tst.sh sample.txt
sql -update .... 11,Client, Disk Proxy Client,192.1680.11
sql -update .... 12,Client,192.1680.12
sql -update .... 56,Client,10.0.10.112
or if you really want 3 separate shell variables for some reason then:
$ cat tst.sh
#!/usr/bin/env bash
while IFS=':' read -r index type location; do
echo sql -update .... "$index,$type,$location"
done < <(
awk '
BEGIN {
FS = "[[:space:]]*:[[:space:]]*"
OFS = ":"
}
$1 ~ /^(Index|Type|Location)/ {
rec = rec sep $2
sep = OFS
}
!NF {
print rec
rec = sep = ""
}
END {
print rec
}
' "${@:--}"
)
Remove the echo
and fix the sql query if I'm right, otherwise update your question with more complete requirements and more truly representative sample input/output.
Note that the above is directly using sample.txt as input, not the output of your existing grep command, we're no longer using that.
CodePudding user response:
If sed
is an option and your expected output is correct (lower case as well as client
being chopped at the ,
), you can try this;
$ sed '/Up/{N;d};s/\([[:alnum:]]\ \)[^[:alnum:]]*\([^,]*\).*/\L\1=\2/' file
index=11
type=client
location=192.1680.11
index=12
type=client
location=192.1680.12
index=56
type=client
location=10.0.10.112