Link to home
Start Free TrialLog in
Avatar of itguy411
itguy411

asked on

sed one liner

I have a file, lets call it /etc/sysconfig/network.

i have a random hostname in the file:

HOSTNAME=randomhostname

I want to replace the whole line HOSTNAME=randomhostname  with my own string HOSTNAME=goodhost

I need a short Send to say  Find  HOSTNAME=whatever and replace it with my correct host name.
ASKER CERTIFIED SOLUTION
Avatar of Morcalavin
Morcalavin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If necessary, you might need to check if the line really starts with HOSTNAME to avoid replacing lines that you don't really want to replace.

Depending on how your file looks like, both of the above mentioned commands work, but you might get the following result:

Let's assume that the file you want to modify looks like this:
---------------------------
HOSTNAME=random1234  # this is the hostname
#HOSTNAME=

#Example: HOSTNAME=something
---------------------------

Using this command now produces the following output:

sed 's/HOSTNAME=.*/HOSTNAME=goodhost/' test.txt
---------------------------
HOSTNAME=goodhost
#HOSTNAME=goodhost

#Example: HOSTNAME=goodhost
---------------------------

So all occurences of HOSTNAME=.* get replaced, wheter they're commented out or not.
I don't know if that's interesting for you, but to only replace HOSTNAME=somethingrandom if not commented, you could use:

sed 's/^HOSTNAME=[^ ]\+/HOSTNAME=goodhost/' test.txt
----------------------------
HOSTNAME=goodhost  # this is the hostname
#HOSTNAME=

#Example: HOSTNAME=something
----------------------------


Indeed. My regex isn't robust(nor was it intended to be).  It fits the strictest interpretation of the data provided.  The third solution should cover all your bases though, unless you have something funky/garbage as your hostname, then you might run into issues.

The second command will not edit the file, but rather spit the results to stdout, so you'll have to redirect it to make it do what you want.

I just pointed out the possible pitfalls and the sed commands used did not replace the text in the file, yes, but it was more about the regex itself.
Avatar of itguy411
itguy411

ASKER

Great job  
Edit in place rocks.  

thank you.