Ank
Ank

Reputation: 51

Substituting values of one column from a list of corresponding values

I want to replace the entries in one column of file input A.txt by the list given in B.txt in corresponding order

For example

A.txt is tab delimited but in a column values are separated by comma need to change one of entries of that column values say P=

1 X y Z Q=Alpha,P=beta,O=Theta
2 x a b Q=Alpha,P=beta,O=Theta
3 y b c Q=Alpha,P=beta,O=Theta
4 a b c Q=Alpha,P=beta,O=Theta
5 x y z Q=Alpha,P=beta,O=Theta

B.txt is

1 gamma
2 alpha
3 alpha
4 gamma
5 alpha

now reading each entry in A.txt and replace P= with the corresponding line values in B.txt

Output:

1 X y Z Q=Alpha,P=gamma,O=Theta
2 x a b Q=Alpha,P=alpha,O=Theta
3 y b c Q=Alpha,P=alpha,O=Theta
4 a b c Q=Alpha,P=gamma,O=Theta
5 x y z Q=Alpha,P=alpha,O=Theta

Thanks in advance!!!

Upvotes: 0

Views: 144

Answers (3)

Tedee12345
Tedee12345

Reputation: 1210

Another solution:

awk '{getline b < "B.txt" split(b, a, FS)} -F "," {sub(/beta/, a[2]); print}' A.txt

Upvotes: 0

Thor
Thor

Reputation: 47099

You could have sed write you a sed script, e.g.:

sed 's:^:/^:; s: :\\b/s/P=[^,]+/P=:; s:$:/:' B.txt

Output:

/^1\b/s/P=[^,]+/P=gamma/
/^2\b/s/P=[^,]+/P=alpha/
/^3\b/s/P=[^,]+/P=alpha/
/^4\b/s/P=[^,]+/P=gamma/
/^5\b/s/P=[^,]+/P=alpha/

Pipe it into a second sed:

sed 's:^:/^:; s: :\\b/s/P=[^,]+/P=:; s:$:/:' B.txt | sed -r -f - A.txt

Output:

1 X y Z Q=Alpha,P=gamma,O=Theta
2 x a b Q=Alpha,P=alpha,O=Theta
3 y b c Q=Alpha,P=alpha,O=Theta
4 a b c Q=Alpha,P=gamma,O=Theta
5 x y z Q=Alpha,P=alpha,O=Theta

Upvotes: 1

dogbane
dogbane

Reputation: 274612

Assuming A.txt and B.txt are sorted on the first column, you can first join both files and then perform the replacement within a specified field using sed:

For example:

join -t $'\t' -j 1 A.txt B.txt | sed 's/,P=.*,\(.*\)\t\(.*\)/,P=\2,\1/g'

Upvotes: 1

Related Questions