[英]Need to replace a specific part of line from a file using shell script
我正在嘗試使用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
另一種使用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
您可以對其進行幾次測試,然后使其自動化,但是除非您正在構建該自動化工具,否則我將親自對其進行檢查。
REPLACEMENT_PATH=mypath
sed -i path/postgresql.conf -re "s/^(data_directory[[:space:]]*=[[:space:]]*')[^']*(')/\1${REPLACEMENT_PATH}\2/"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.