Search for a value and replace other field in the same set

Hello friends,

I have huge file with many sets where each "set" has few lines and each set always begins with "Set" in Sq brackets as shown above.

# cat file1

[Set 1]
[Name "rnd"]
[Date "2013.12.03"]
[Result "WIN"]
[VALUE "A1B2C3"]

[Set 2]
[Name "rnd"]
[Date "2013.12.03"]
[Result "WIN"]
[VALUE "X9Y8Z7"]

[Set 3]
[Name "rnd"]
[Date "2013.12.03"]
[Result "WIN"]
[VALUE "P4Q5R6"]

Now I need to grep for a value and modify its result field. ex.

./script.sh  file1   X9Y8Z7   LOSS  >file2 

first parameter is input file 2nd parameter is value to be searched and 3rd parameter is new value.
then file2 should have the new values like below:

# cat file2

[Set 1]
[Name "rnd"]
[Date "2013.12.03"]
[Result "WIN"]
[VALUE "A1B2C3"]

[Set 2]
[Name "rnd"]
[Date "2013.12.03"]
[Result "LOSS"]
[VALUE "X9Y8Z7"]

[Set 3]
[Name "rnd"]
[Date "2013.12.03"]
[Result "WIN"]
[VALUE "P4Q5R6"]

I think we can do this using awk but i have no idea. Pls help me!
Thanks!!

awk -v S="X9Y8Z7" -v  R="LOSS" '
        /Result/ {
                v = $0
                getline
                if ( $2 ~ S )
                sub ( /\"[A-Z]*\"/, "\"" R "\"", v )
                $0 = v RS $0
        }
        1
' file1
2 Likes

try this script:

infile=$1
val="$2"
new="$3"
awk -vv="$val" -vn="$new" '
$0 ~ "VALUE \"" v "\"" {
    gsub("[[]Result[^\n]*\n", "[Result \"" n "\"]\n")
}
1' RS='' ORS='\n\n' OFS='\n' $infile
1 Like