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

问题描述 投票:1回答:3

我正在尝试使用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 shell ubuntu
3个回答
2
投票

使用case的另一种方法 - *允许在等于和任何评论之前的非精确间距,但引入了错误匹配的小可能性。我认为对于线路上的其他特定信息,它足够小,以至于它不是问题。

$: cat postgresql.conf
some stuff
data_directory = '/var/lib/postgresql/10/main'         # use data in another directory
some other stuff.

$: path=/new/path/to/
$: while IFS='' read -r line || [[ -n "$line" ]]
>  do case "$line" in
>     data_directory*=*'/var/lib/postgresql/10/main'*) 
>        echo "${line//\/*\//$path}";;
>     *) echo "$line";;
>     esac
>  done < postgresql.conf >/tmp/checkme
some stuff
data_directory = '/new/path/to/main'         # use data in another directory
some other stuff.

如果它很好,那么

mv /tmp/checkme postgresql.conf

您可以测试几次,然后将其自动化,但除非是您正在构建的持续自动化,否则我会亲自检查它。


3
投票

普通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

1
投票
REPLACEMENT_PATH=mypath
sed -i path/postgresql.conf -re "s/^(data_directory[[:space:]]*=[[:space:]]*')[^']*(')/\1${REPLACEMENT_PATH}\2/"
© www.soinside.com 2019 - 2024. All rights reserved.