从文件中删除多行变量内容

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

我正在尝试编写一个 Bash 脚本来处理 /etc/pacman.conf 中的 Pacman 存储库,该脚本可在脚本中使用,而不依赖于文本编辑器所需的用户交互。

我在弄清楚删除选项时遇到了麻烦。如何根据多行变量的内容从文件中删除多行或一段?

所以我有这个多行变量

echo "$repo_query_result"

它的内容看起来像这样

[repo-name]
Server = https://host.domain/$arch

或者例如像这样的禁用回购

#[repo-testing]
#SigLevel = PackageRequired
#Include = ./repo-2-mirrorlist

当我尝试使用以下与单行变量一起使用的命令时

sed "/$repo_query_result/d" /etc/pacman.conf

我得到以下错误

sed: -e expression #1, char 6: unterminated address regex

我能找到的关于

sed
awk
和多行变量的所有内容,其中有关如何从变量中删除单行的解决方案。或者在删除段落时,它总是一个固定的模式,例如相同的开始和结束词,这不适合我的情况。

bash variables sed multiline pacman-package-manager
1个回答
0
投票

这样的东西行得通吗?

#!/bin/bash

# Multiline variable containing the content to be removed
repo_query_result="[repo-1-name]
Server = https://host.domain/\$arch
"

# Create a temporary file
tmp_file=$(mktemp)

# Copy the original file to the temporary file, excluding the lines to be removed
sed "/$repo_query_result/Id" /etc/pacman.conf > "$tmp_file"

# Overwrite the original file with the temporary file
mv "$tmp_file" /etc/pacman.conf

# Remove the temporary file
rm "$tmp_file"
© www.soinside.com 2019 - 2024. All rights reserved.