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

Time:12-15

This might look simple, But I could not get it work. I have a property file and contains like below.

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

In my bash script, I do some processing and modifying available cols property and trying to replace it in the file. Like below.

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

The above script works fine if my property file has only AVAIL_COLS property and not SC_AVAIL_COLS. But if the property file contains SC_AVAIL_COLS property, then instead of replacing the line, it adds as a new line in the file making duplicate entry in the file.

How to replace the AVAIL_COLS property line directly? The line number or the order of properties in file may vary. So I was looking for a generic way.

Expected OUTPUT

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

CodePudding user response:

You can fix your script like this:

propfile="$1"
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"

However all this can be done in a single awk command also like this:

awk -v val=',col6,col7,col8' -F= '$1 == "AVAIL_COLS" {
$0 = $0 val} 1' file

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

CodePudding user response:

You need to differentiate between the two lines, because the second line matches too in your condition.

Try including ^ for beginning of line like this:

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

CodePudding user response:

You can change your sed command to the following to match only the single line.

available_cols=",col6,col7,col8"
$ sed -i.bak "/^$line_avail_cols/s/$/$available_cols/" $propfile
AVAIL_COLS=col1,col2,col3,col4,col5,col6,col7,col8
SC_AVAIL_COLS=col1,col2,col3
  • Related