I am pretty new to awk, and I am trying to modify an existing script, here is my requirement - from command line provide a string parameter like - "abcd|efgh|ijkl" (I am able to do this using -v) and the split it to have a array of strings like - {"abcd","efgh","ijkl"). Read values from a file and if a particular string matches one of the values in the split array(the value will be a key-val pair ex - abcd:789), then replace it and write it in the output file.(in output file i need to have "abcd 123") for other lines if the key doesn't matches any value in my array,(for example "xyz:456") I want to print the actual value ("xyz 456") here is how I am getting the split array -
awk -v mystring="$5" 'BEGIN {
print mystring ; //prints abcd|efgh|ijkl
split(mystring,mylistDictionary,"|"); //splitting
for (i in mylistDictionary) uniqueKeys[mylistDictionary[i]] = "" //* currently unused
print "1-",mylistDictionary[1]; // prints abcd
print "2-",mylistDictionary[2]; // prints efgh
}
.
.
.
function writeLine(line) {
split(line,lineTokens,"="); // the line will be something like abcd = ewiubqq
for(x in mylistDictionary) {if(x==lineTokens[1]){ tmp="123"; print lineTokens[1],tmp; } };
print(line)
}
I am able to print the value of lineTokens[1]
inside the for loop , and I am also able to print all values of the array (if i replace the if block with print x;
but, when I am trying to compare the two values if(x==lineTokens[1])
, the condition is never true and I am unable to change the value of tmp
.
i understand that awk arrays are associative, and so based on some answers tried to convert it into an array with the values as keys,which is the line with the *
in the comment , but using that also doesn't works.
Sample input -
key1 = value1
key2 = value2
key3 = value3
key1 = value4
command line arg- "key1|key2|key8"
Expected output-
key1 = 123
key2 = 123
key3 = value3
key1 = 123