0

I am trying to replace a string where a specific condition is true in the same line using awk variables.

I found something that could help me a lot but I'm facing a new challenge cause a I need to do this using variables.

Here an example of my content file.

0;20220808163547;
1224;20220808163547;
1224;20220808170514;
0;20220808170514;

I need always to replace the first column when the second column match the value 20220808170514.

Thanks to other post I could accomplish it. https://stackoverflow.com/questions/20664446/bash-replace-string-where-specific-condition-is-true

This works fine.

awk '/20220808170514/ {sub(/0/,"2048")}1' FileName.ctrl

But I need to do this in a dynamic way.

v1=2048
v2=20220808170514
awk -v var1="$v1" -v var2="$v2" '/var2/ {sub(/0;/,var1";")}1' FileName.ctrl

But it didnt work.

0;20220808163547;
0;20220808163547;
0;20220808170514;
0;20220808170514;

I need something like this

0;20220808163547;
1224;20220808163547;
2048;20220808170514;
2048;20220808170514;

PS: v1 and v2 it'll be different among the time.

1

1 Answer 1

2

I would suggest something like this:

$ awk -v FS=';' -v OFS=';' -v var1="$v1" -v var2="$v2" '$2 == var2 { $1 = var1 } 1' filename 
0;20220808163547;
1224;20220808163547;
2048;20220808170514;
2048;20220808170514;

First, the way to match the line against a pattern in a variable would be $0 ~ var. Just /var/ would take that as a literal regex. Then, sub(/0;/, ...) would only replace the first field if it's 0, it wouldn't replace 1224.

But if we set the field separators correctly, we can just if the second field ($2) is identical to the value in the variable, and then we can just replace the first field ($1). It requires setting the input and output field separators (FS and OFS) to the ; used in your file.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .