Sed, awk or another bash command to modify string with the content of another file

Hello everybody,

I would like modify some strings using sed or another command line with the content file.

For example:

- {fqdn: "server-01" , ip: "server-01"}
- {fqdn: "server-02" , ip: "server-02"}
- {fqdn: "server-03" , ip: "server-03"}
- {fqdn: "server-04" , ip: "server-04"}

My goal is to remplace server01, server02 etc with the content of the following file:

cat /tmp/new_server
server-05
server-06
server-07
server-08

Do you have any idea to do that using AWK or SED ?

Thanks.

Welcome!

What is more important than "our ideas" is what is your idea and what code have you tried and what output and / or errors did you get?

Along with the other questions:-

  • Are you logically looking to just add 4 to the server number, or do you need to work out the highest numbered server and count on from there?
  • Are these decimal server numbers, hexadecimal, looked up from a list or something else perhaps?
  • What happens if you reach server 100, whatever your number format?

Kind regards,
Robin

The following bash script replaces each server-* in file "your_example" with an item from file "new_server".
Bash needs an extra descriptor (here: 3) to open the second file.

#!/bin/bash
# glob-match for a server name
server_m="server-[0-9][0-9]"
while IFS= read -r line
do
  if [[ $line == *$server_m* ]]
  then
    read server_n <&3
    line=${line//$server_m/$server_n}
  fi
  echo "$line"
done < your_example 3< new_server

The same with awk, here a more powerful and precise ERE-match is used:

awk '
BEGIN {
# ERE-match for a server name
  server_m="\<server-[0-9]+"
}
$0~server_m {
  getline server_n < servers
  gsub(server_m,server_n,$0)
}
{ print }
' servers="new_server" your_example

How about

paste file[12] | awk '{gsub (/server-0[0-9]/, $NF); NF--} 1'

or

paste file[12] | sed -r 's/^(.*)((server-0)[0-9])(.*)\2(.*)(\3[0-9])/\1\6\4\6\5/'