bash 由于更多匹配项,未替换匹配字符串中的一行

bash not replacing a line on matching string due to more match

这可能看起来很简单,但我无法让它工作。我有一个 属性 文件,包含如下内容。

AVAIL_COLS=col1,col2,col3,col4,col5
SC_AVAIL_COLS=col1,col2,col3

在我的 bash 脚本中,我做了一些处理和修改可用的列 属性 并尝试在文件中替换它。如下所示。

propfile=<my property file>
line_avail_cols="AVAIL_COLS="
line_sc_avail_cols="SC_AVAIL_COLS="
available_cols=$(grep $line_avail_cols $propfile | grep -v $line_sc_avail_cols)

# Doing some operations to add few more values to same row.
available_cols="$available_cols,col6,col7,col8"

#Replace the line with new content
sed -i '/'"$line_avail_cols"'/c\'"$available_cols" $propfile

如果我的 属性 文件只有 AVAIL_COLS 属性 而没有 SC_AVAIL_COLS,则上述脚本工作正常。 但是如果 属性 文件包含 SC_AVAIL_COLS 属性,那么它不会替换该行,而是在文件中添加一个新行,从而在文件中创建重复条目。

如何直接替换AVAIL_COLS属性行?文件中的行号或属性顺序可能会有所不同。所以我一直在寻找一种通用的方式。

预期输出

AVAIL_COLS=col1,col2,col3,col4,col5,col6,col7,col8
SC_AVAIL_COLS=col1,col2,col3

你需要区分这两行,因为第二行也符合你的条件。

尝试在行首包含 ^,如下所示:

sed -i '/^'"$line_avail_cols"'/c\'"$available_cols" $propfile

您可以像这样修复您的脚本:

propfile=""
line_avail_cols="AVAIL_COLS="
line_sc_avail_cols="SC_AVAIL_COLS="
available_cols="$(grep "^$line_avail_cols" $propfile)"

# Doing some operations to add few more values to same row.
available_cols="$available_cols,col6,col7,col8"

#Replace the line with new content
sed -i "s/^$line_avail_cols.*/$available_cols/" "$propfile"

然而,所有这些都可以在一个 awk 命令中完成,也像这样:

awk -v val=',col6,col7,col8' -F= ' == "AVAIL_COLS" {
[=11=] = [=11=] val} 1' file

AVAIL_COLS=col1,col2,col3,col4,col5,col6,col7,col8
SC_AVAIL_COLS=col1,col2,col3