Michael Hegner
Michael Hegner

Reputation: 5823

Shell Script Edit Files Line

I am not that good on linux shell script and I need little help.

I want to edit a file via script (finding the line and edit).

The Original line is:

# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=< hostname >"

I want to uncomment and replaye hostname with 127.0.0.1

JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=127.0.0.1"

Upvotes: 1

Views: 1915

Answers (3)

janos
janos

Reputation: 124648

Here's one way to do it:

sed -i -e 's/# \(JVM_OPTS=.*=\).*/\1127.0.0.1"/' path/to/file

That is, replace the line with the text captured within the group \(JVM_OPTS=.*=\), so everything from JVM_OPTS= until another = sign, and append 127.0.0.1" to the end.

If there might be other lines in the file starting with # JVM_OPTS=, then you could make the pattern matching more strict, for example:

sed -i -e 's/# \(JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=\).*/\1127.0.0.1"/' path/to/file

Upvotes: 3

Bruce David Wilner
Bruce David Wilner

Reputation: 469

Fine answers, but they don't do anything by way of TEACHING the gentleman how and why it works.

If you were using the mundane text editor, ed, you would use three commands after invoking the command "ed filename":

s/^# //
s/< hostname>/127.0.0.1/
w

So, you can use a pipe to submit those commands directly to ed, specifying "-" as its first argument so that it doesn't bother you by reporting character counts upon reading in and writing out the file:

( echo 's/^# //'; echo 's//127.0.0.1/'; echo w ) | ed - filename

You don't need to echo 'q' also because ed will automatically quit when it runs out of input or encounters "end of file" (you can simulate this on the keyboard by just hitting the CTRL-D key rather than actually typing q ).

Upvotes: 3

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can refer to the set command, change the filename with the name you are working at,

sed -i 's@# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=< hostname >"@JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=127.0.0.1"@' filename

Upvotes: 3

Related Questions