首页 > 解决方案 > 需要使用 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如果没有,也可以只用更改的部分替换整条生产线。谢谢!

标签: bashshellubuntu

解决方案


简单的 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

推荐阅读