Skip to content
Advertisement

how to change unique values within a specific column in a file to another value in linux?

I have a file like this:

 col1 col2 col3
  1 1 1
  2 1 2
  3 1 1
  23 2 2
  2 1 1
  3 2 2
  2 2 2

I want in the second colum all the rows with value 1 be changed into 4. so output should be:

 col1 col2 col3
  1 4 1
  2 4 2
  3 4 1
  23 2 2
  2 4 1
  3 2 2
  2 2 2

any suggestion?

Advertisement

Answer

You can use an awk ternary operator for that,

awk '{$2=(($2=="1")?"4":$2)}1' file

Since by default awk splits input fields by a single white-space, we can directly check $2 to contain value as 1 if so we can replace it as 4 else keep the value itself. The {}1 will print the file with the updates to the fields.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement