简体   繁体   中英

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"

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

您可以参考set命令,使用您正在使用的名称更改文件名,

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

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM