In my ubuntu instance I have a file which looks like this, actually is not a file but an output of the following command:
cat wghub.conf | egrep '.conf|AllowedIPs' | grep -v configuration | awk '{print $3}'|cut -d "/" -f1|tr "n" " "|xargs -n 2
samsung 10.88.188.11
ultra 10.88.188.12
mi10 10.88.188.13
drunksorrow 10.88.188.15
win11 10.88.188.16
jderu 10.88.188.17
I also have a second file generated by crontab once per minute:
Client: 10.88.188.13, Latest Handshake: 1 minute, 42 seconds
Client: 10.88.188.16, Latest Handshake: 51 minutes, 32 seconds
I need to replace the IP with the correspondent name from the 1st file into the 2nd file so the desired result will be:
Client: mi10, Latest Handshake: 1 minute, 42 seconds
Client: win11, Latest Handshake: 51 minutes, 32 seconds
How can I achieve this with bash?
I tried in so many ways with no results.
Thank you!
I have no results because I can’t join the IPs from the both files in order to format the second file as I want
3
Answers
Append this to your pipe to generate the necessary commands for
sed
in a file:Then execute:
Output:
In bash you can use associative array (map):
Output:
You can also skip address substitution if name is unknown. Second
while
loop will be:FWIW, once you pull
awk
into the mix you can usually eliminate the need for other tools likecat
,(e)grep
,cut
,tr
,sed
, and in this casexargs
.awk
is also quite useful when trying to join/match different files. Net result: OP’s entire process can probably be performed with a singleawk
script (which in turn is going to be more efficient than the current method).OP hasn’t (yet) provided a copy of
wghub.conf
so I’ve reverse engineered OP’s code to come up with a file which, when fed to OP’scat/grep/egrep/awk/cut/tr/xargs
pipeline, will generate the same set of hostname/ip pairs:I’ve also added a bogus line to OP’s crontab output to demonstrate leaving an ip address alone if there is no match in
wghub.conf
One
awk
approach to replacing all of OP’s current code that also performs the match with the crontab output:This generates:
NOTES:
I want to replace something in a file
but it’s not clear (to me) if OP wants to update the file containing the crontab outputGNU awk
(akagawk
) then it would be possible to use the-i inplace
feature to update the crontab file; OP can read up on that and ask a new question if there are issues getting it to work (it’s a bit more involved when you only want to update some of the files fed toawk
)awk
output to a tmpfile, (optional) make a backup copy ofcrontab.out
, thencp tmpfile crontab.out