bash - 需要使用 shell 脚本从文件中替换行的特定部分
问题描述
我正在尝试path
使用 shell 脚本从 postgresql.conf 替换以下行的一部分:
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
推荐阅读
- redux-saga - 轮询多个端点时,Redux Saga 产生非常缓慢
- ios - MKPolyline 不在地图上绘制。我该如何解决这个问题?
- r - 以给定字符串结尾的列的 Pmax
- python - 如何在不预先定义可以输入的值数量的情况下将多个项目附加到列表中?
- python - 无法修复 JSONDecodeError:无效的控制字符
- linux - 带有 sudo 的卷曲返回连接被拒绝,但普通卷曲运行良好
- windows - 使用 IO.File.Copy() 复制时,系统日期格式导致文件中的日期发生更改
- python - Scrapy - 产生新的请求不在循环中工作
- microsoft-graph-api - 使用图形 API 在 O365 中不可编辑的日历事件
- php - 在 WooCommerce 中停止从机器人注册特定 Web 域