I have a file config.txt which consist of lines like below
$ cat config.txt | head -n 3
[email protected]:26601
[email protected]:26604
[email protected]:26607
$ cat ip.txt | head -n 3
10.0.4.5
10.3.5.6
10.3.5.8
I would like to replace the IP address on config.txt with ip's on ip.txt file respectively
the expected output is
[email protected]:26601
[email protected]:26604
[email protected]:26607
Since the ip's in config file are dynamic, I need to use regex in sed to replace the IP. for an example:
$ echo "[email protected]:26601" | sed "s/*@\ :*/*@10.0.4.5:*/g"
but its not updating the ip's. I am very new to the regex in scripting. Kindly help!
CodePudding user response:
Well, in this case it is possible to use sed
and a regex. You could first join the files and then use regex to shuffle lines:
paste config.txt ip.txt | sed 's/@[^:]*\(.*\)\t\(.*\)/@\2\1/'
Note that sed
works in the context of a single line only. But a regex is not "dynamic", if the ip's in config file are dynamic
then you should use something "more" then regex, better a full programming language with support for maps and internal state, like awk
but also perl
or python
.
CodePudding user response:
A way using awk
instead. It first reads ip.txt
and stores its contents in an array indexed by line number, and then for each line of config.txt
, replaces the IP address in it with the one from the corresponding line of ip.txt
:
$ awk 'FNR==NR { ips[FNR] = $0; next }
{ sub(/@[^:] :/, "@" ips[FNR] ":"); print }' ip.txt config.txt
[email protected]:26601
[email protected]:26604
[email protected]:26607