bash - 需要使用 shell 脚本从文件中替换行的特定部分

标签 bash shell ubuntu

我正在尝试使用 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/

相关文章:

python - Bash 脚本与用于 Shell-Command-Heavy 实用程序的 Python 脚本的优点

linux - 从命令行启动 matlab 后,linux 终端中缺少某些内容

linux - 如何在没有查找的情况下在 linux shell 脚本中根据日期查找和删除文件?

shell - 如何重定向 Tornado/VXWorks shell 输出?

python - 如何使用 Python 从结果文件中获取设备的特定详细信息

ubuntu - Asterisk 和 a2billing 通话问题

bash - 出现错误 : sed: -e expression #1, 字符 2:未知命令: `.'

bash - 如果存在 `set -e` 指令,为什么 ((0)) 会导致 Bash 脚本退出?

linux - 使用 shell 脚本为每一行添加后缀

python - 尽管使用 pip 和 sudo apt-get install 安装,但在 Ubuntu 上找不到 Pandoc