我正在尝试使用 shell 脚本从 postgresql.conf 替换下一行的 path
部分:
data_directory = '/var/lib/postgresql/10/main' # use data in another directory
我首先检查了我是否能够使用下面的脚本首先找到该行,但没有找到该行:
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
if [[ "$line" = "data_directory = '/var/lib/postgresql/10/main' # use data in another directory" ]]
我知道有更好的方法可以使用 sed
替换这一行,但我需要通过从头到尾读取文件然后替换该行的所需部分来知道它是否可行,如果成立。如果没有,只用更改的 path
部分替换整行也可以。谢谢!
最佳答案
普通 bash 解决方案:
path="/newpath"
while IFS= read -r -d $'\n'; do
if [[ "${REPLY}" == "data_directory = '/var/lib/postgresql/10/main' # use data in another directory" ]]
then echo "${REPLY/\'*\'/'${path}'}"
else echo "${REPLY}"
fi
done < postgresql.conf > new.conf
mv new.conf postgresql.conf
测试:
$ cat postgresql.conf
# This is a comment
log_connections = yes
log_destination = 'syslog'
search_path = '"$user", public'
shared_buffers = 128MB
data_directory = '/var/lib/postgresql/10/main' # use data in another directory
# This is a comment
$ path="/newpath"
$ while IFS= read -r -d $'\n'; do
> if [[ "${REPLY}" == "data_directory = '/var/lib/postgresql/10/main' # use data in another directory" ]]
> then echo "${REPLY/\'*\'/'${path}'}"
> else echo "${REPLY}"
> fi
> done < postgresql.conf
# This is a comment
log_connections = yes
log_destination = 'syslog'
search_path = '"$user", public'
shared_buffers = 128MB
data_directory = '/newpath' # use data in another directory
# This is a comment
关于bash - 需要使用 shell 脚本从文件中替换行的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53815035/