Conditional replacement of columns in a text file

Hello scriping expert friends,

I have 2 requirements on replacing fields of text files:

I have lot of data with contents like below:

[FEN "1rr2b1k/3q1P1p/p4p2/1pp1p2B/2PpP2P/1P1P4/P3Q3/R1B3RK w - - 0 33"]
[FEN "2bqk1r1/p4p2/1p2pQp1/1n1pP1Bp/7P/3P2N1/P4PP1/6K1 w - - 0 3"]
[FEN "2q3kr/6r1/1p2N3/5p2/1P1p4/6R1/7P/6K1 w - - 0 3"]
[FEN "2r2r1k/pp1q1p1p/3bpn2/5P2/1P6/P3P3/1B3P1P/R3K1R1 w Q - 0 2"]

Requirement-1:

The digit after 0 should always be changed to 1

[FEN "1rr2b1k/3q1P1p/p4p2/1pp1p2B/2PpP2P/1P1P4/P3Q3/R1B3RK w - - 0 1"]
[FEN "2bqk1r1/p4p2/1p2pQp1/1n1pP1Bp/7P/3P2N1/P4PP1/6K1 w - - 0 1"]
[FEN "2q3kr/6r1/1p2N3/5p2/1P1p4/6R1/7P/6K1 w - - 0 1"]
[FEN "2r2r1k/pp1q1p1p/3bpn2/5P2/1P6/P3P3/1B3P1P/R3K1R1 w Q - 0 1"]

Requirement-2:

if 3rd column value is "w" (just before hyphens) then I should make it to "b" and vice-versa.

[FEN "1rr2b1k/3q1P1p/p4p2/1pp1p2B/2PpP2P/1P1P4/P3Q3/R1B3RK b - - 0 33"]
[FEN "2bqk1r1/p4p2/1p2pQp1/1n1pP1Bp/7P/3P2N1/P4PP1/6K1 b - - 0 3"]
[FEN "2q3kr/6r1/1p2N3/5p2/1P1p4/6R1/7P/6K1 b - - 0 3"]
[FEN "2r2r1k/pp1q1p1p/3bpn2/5P2/1P6/P3P3/1B3P1P/R3K1R1 b Q - 0 2"]

I could get them done but with some poor scripting. I read value of each column and compare and echoing to another file but I guess awk/sed would do so much effecient. I have no idea how to use awk.:o

Please provide me 2 different commands separately as sometimes I may have to do only one of them.

TIA

$ awk 'sub(/[[:digit:]]+/,new,$NF)' new="1" file
[FEN "1rr2b1k/3q1P1p/p4p2/1pp1p2B/2PpP2P/1P1P4/P3Q3/R1B3RK w - - 0 1"]
[FEN "2bqk1r1/p4p2/1p2pQp1/1n1pP1Bp/7P/3P2N1/P4PP1/6K1 w - - 0 1"]
[FEN "2q3kr/6r1/1p2N3/5p2/1P1p4/6R1/7P/6K1 w - - 0 1"]
[FEN "2r2r1k/pp1q1p1p/3bpn2/5P2/1P6/P3P3/1B3P1P/R3K1R1 w Q - 0 1"]

$ awk '{$(NF-4)=new}1' new="b" file
[FEN "1rr2b1k/3q1P1p/p4p2/1pp1p2B/2PpP2P/1P1P4/P3Q3/R1B3RK b - - 0 33"]
[FEN "2bqk1r1/p4p2/1p2pQp1/1n1pP1Bp/7P/3P2N1/P4PP1/6K1 b - - 0 3"]
[FEN "2q3kr/6r1/1p2N3/5p2/1P1p4/6R1/7P/6K1 b - - 0 3"]
[FEN "2r2r1k/pp1q1p1p/3bpn2/5P2/1P6/P3P3/1B3P1P/R3K1R1 b Q - 0 2"]
1 Like

Thank you Akshay Hegde,

First one works great.

Second one always makes it to "b". As I said in my first post, we need it vice-versa. For ex. it should change to "w" if it already has "b" and it should change to "b" if it has "w".

Thanks a lot!

Okay this would be fine, assuming possibilities are only either "b" or "w"

$ awk '{$(NF-4)=$(NF-4)=="b"?"w":"b"}1' file