Érdekességképp itt van, amit nekem dobott, és ez tetszik is, alighanem erre megyek majd:
You can replace the loop with a single awk command to streamline the process. Here is an approach to achieve that:
- Read the
HostNamevalues into an array. - Use
awkto process theCACHEFILEfor all hostnames at once. - Use
awkto generate the SQL update statements.
Here's how you can do it:
awk -v CACHEFILE="${CACHEFILE}" '
BEGIN {
# Load hostnames into an array
while ((getline hostname < "hostnames.txt") > 0) {
hostnames[hostname]
}
close("hostnames.txt")
}
{
# Process each line of CACHEFILE
if ($NF in hostnames) {
if ($1 > timestamps[$NF]) {
timestamps[$NF] = $1
}
}
}
END {
for (hostname in timestamps) {
if (timestamps[hostname] > 0) {
printf "UPDATE servers set backup=\"%s\" WHERE hostname=\"%s\";\n", timestamps[hostname], hostname >> "'${SQLFILE}'"
}
}
}
' "${CACHEFILE}"
Explanation:
-
BEGIN Block:
- Read the hostnames from a file (
hostnames.txt), where each line contains aHostName. Store these hostnames in an array.
- Read the hostnames from a file (
-
Main Block:
- For each line of the
CACHEFILE, check if the last field ($NF) is in the array of hostnames. - If it is, and if the first field (
$1) is greater than the current maximum timestamp for that hostname, update the timestamp for that hostname.
- For each line of the
-
END Block:
- For each hostname, if there is a valid timestamp, print the SQL update statement to the
SQLFILE.
- For each hostname, if there is a valid timestamp, print the SQL update statement to the
Replace "hostnames.txt" with the path to your file containing the list of hostnames. This approach ensures that you process all hostnames and generate the SQL update statements in one go, avoiding the need for a loop.