I have a list similar to the following:    sometext.com    moretext.com
192.564.7.3    hello.com

Output I need:    sometext.com    moretext.com
192.564.7.3    hello.com

I want to remove IPs that do not have a hostname only if they already have a row that includes a hostname.

See above for example.

Is this possible to do?

  • It seems to me that you’re not so much sorting as filtering — is it fair to say you want to remove ip addresses that do not have hostnames associated with them? Try explaining in words — in your question— what you want to have happen.
    – Jeff Schaller
    May 24, 2018 at 12:21

1 Answer 1


Here is awk solution (I assume order of output is not matter).

awk '!seen[$1]{ seen[$1]=$0; next } $2!=""{ seen[$1]=$0 } 
    END{ for (x in seen) print seen[x] }' infile

Here we define an associated array named seen and $1 as key index of that; so we are checking for the key of first column which are IPs not exist in array !seen[$1] then add whole line $0 to that key's value and read next line; otherwise (where IP already seen before and exist in array) if next line had same IP and has hostname then update that key's value with current line value.

At the END we are looping over array seen with variable x as refereeing to the array indexes and print the values of those keys.

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.