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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
ASKER
Great job
Edit in place rocks.
thank you.
Edit in place rocks.
thank you.
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=go
--------------------------
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
--------------------------