Cat Kerr
Cat Kerr

Reputation: 149

Replacing an entry in a row with another entry specified on the same row.. how do I do this for multiple rows?

I am quite new to using linux and command line but am learning it for work. I can do most of the basics, however I am stuck on something.

I currently have a .txt file that looks like this:

A B 1 1 1 1 0 0 0 0 1 0 1 0

B F 1 0 0 0 1 1 0 1 1 1 0 1

F G 0 0 0 0 0 0 0 0 0 0 1 0

Ie. there are two letters at the start of each row - every number '0' written in the same row corresponds to the first letter, and every number '1' written in the same row corresponds to the second letter. It is space delimited.

What I would like to do is to replace every 0 and 1 with the corresponding letter on that row.

So the above passage would turn into:

A B B B B B A A A A B A B A

B F F B B B F F B F F F B F

F G F F F F F F F F F F G F

Does anyone know how I can do this using awk or sed (or a better way)?

Thank you!

Upvotes: 0

Views: 61

Answers (1)

fedorqui
fedorqui

Reputation: 289965

Use gsub:

$ awk '{gsub(0, $1); gsub(1, $2)} 1' your_file
A B B B B B A A A A B A B A
B F F B B B F F B F F F B F
F G F F F F F F F F F F G F
  • gsub(0, $1) replaces every 0 with $1. And $1 is the first field.
  • gsub(1, $2) replaces every 1 with $2. And $2 is the second field.
  • these commands are enclosed within brackets and to have the output printed the write a true condition like 1, so that the default awk behaviour (print $0) is done.

Upvotes: 3

Related Questions