how to delete a line from file using awk filtered by some string

Posted by embedded on Stack Overflow See other posts from Stack Overflow or by embedded
Published on 2010-04-18T15:36:21Z Indexed on 2010/04/18 15:43 UTC
Read the original article Hit count: 150

Filed under:
|
|

I have a file delimited by space. I need to write an awk command that receives a host name argument and it should replace the host name if it already defined in the file. It must be a full match not partially - if the file contains this host name: localhost searching for "ho" will fail and it will be added to the end of the file.

another option is a delete: again awk receives host name argument and it should remove it from the file if exists.

This is what I have so far: (It needs some enhancements)

if [ "$DELETE_FLAG" == "" ]; then
        # In this case the entry should be added or updated
        #    if clause deals with updating an existing entry
        #    END clause deals with adding a new entry
        awk -F"[ ]" "BEGIN { found = 0;} \
                { \
                        if ($2 == $HOST_NAME) { \
                                print \"$IP_ADDRESS $HOST_NAME\"; \
                                found = 1; \
                        } else { \
                                print \$0; \
                        } \
                } \
                END { \
                        if (found == 0) { \
                                print \"$IP_ADDRESS $HOST_NAME\";
                        } \
                } " \
        /etc/hosts > /etc/temp_hosts

else
        # Delete an existing entry
        awk -F'[ ]' '{if($2 != $HOST_NAME) { print $0} }' /etc/hosts > /etc/temp_hosts
fi

Thanks

© Stack Overflow or respective owner

Related posts about awk

Related posts about linux