1

I have a rather large config file that has server short names in it like this:

[host 1]
host = server1

[host 2]
host = server2

[host 3]
host = server3

I need to replace all the server short names with the fq long names that will be outputted from a bash script I've already written, lookup.sh. Can I work some sed or awk magic to accomplish this task?

3
  • 1
    what have you tried to do? using sed is of course possible, but let us know what you tried to do before. – BitsOfNix Mar 28 '16 at 18:28
  • How do you call lookup.sh? lookup.sh <hostname>? – Will Mar 28 '16 at 19:39
  • "lookup.sh server1" will output server1.server.domain.com, of course this function could be added to the main search and replace script instead of calling it out. – Joe Mama Mar 28 '16 at 20:00
1

Your question implied the use of sed or awk, but you didn't explicitly rule out perl 😉

#!/usr/bin/perl
while (<>)
{
    if (/^host = (.+)/) {
        print "host = " . `./lookup.sh $1`;
    }
    else { 
        print;
    }
}

Upon further reflection, the same could be done in awk as follows:

#!/bin/bash

INFILE=$1

awk 'BEGIN { FS = " = " } ; {
        if ($1 == "host") {
                "'"./lookup.sh "'" $2 | getline fqdn
                $2 = "="; $3 = fqdn
        }
        print
}' $INFILE
4
  • Hah, I was asking for it... Yeah perl will work, thank you. Personally I try to do everything in bash but you can't argue with results. Thanks again, just tested and it does what I need. – Joe Mama Mar 28 '16 at 22:01
  • Now if someone can tell me how to do the above in bash :) – Joe Mama Mar 28 '16 at 22:01
  • @JoeMama I just included a pure bash/awk solution in the answer. – Guido Mar 28 '16 at 23:01
  • Of course, that's a pure bash/awk solution in the same sense that the perl script is a pure bash/perl solution. awk is no more a part of "pure" sh or bash than perl is, it's just another external (to sh/bash) scripting language. – cas Mar 29 '16 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.