Changing values in the first column.

I have a file which looks like this:

1 3 5 5 3 2
1 5 3 6 3 2
0 5 6 3 2 9
0 4 5 6 4 9

In the first column, instead of 1, I want to place +1 and instead of 0, I want -1 to be put. So the generated file should look like this:

+1 3 5 5 3 2
+1 5 3 6 3 2
-1 5 6 3 2 9
-1 4 5 6 4 9

Just to let people know what I have done, which to many will look very inefficient. This is why I am interested in knowing a quick solution to this. I first extracted the first column using the following command:

awk '{print $1}' input_file > output_file

Then separated the 1s and 0s in two separate files using the following command:

awk '{ print > $1 ".dat" }' input_file

Then added + before 1, and subtracted -1 from the file that contained 0. Then used cat to append the contents from the .dat files. Then used the paste command to paste the contents with the original file. This process is of course too time consuming. I am using Linux with BASH.

awk '{ if( $1 == 1) $1 = "+1"; else if ($1 == 0) $1= "-1"; print;}' inputfile

If you have the first column to be 1 and 0 only, then use awk '{ if( $1 == 1) $1 = "+1"; else $1= "-1"; print;}' inputfile

1 Like

Or use sub function:

awk '{sub(1,"+1",$1);sub(0,"-1",$1)}1' file
1 Like

Sub fails in this condition, it just replaces first occurrence

# Yoda's
$ cat << test | awk '{sub(1,"+1",$1);sub(0,"-1",$1)}1'
11
00
test

+11
-10

# PikK45
$ cat << test | awk '{ if( $1 == 1) $1 = "+1"; else if ($1 == 0) $1= "-1"; print;}'
11
00
test

11
-1

If the 1st field can only be 0 or 1, you can also try:

awk '{$1 = $1 ? "+1" : -1}1' input_file

Yes, in my case the first column contains only 0 and 1. However, it is good to see others generalize to other values.

This is what I thought after seeing @Akshay's analysis

awk '{ 
  if( length($1) == 1 ) {
    if( $1 == 1) $1 = "+1"; 
    else if ($1 == 0) $1= "-1"; 
  }
  print;}' input.txt

if( length($1) == 1 ) is not needed since 00 is 0 only, if he/she is treating 00 as char then length($1) would be necessary, and your old solution was right I think.

@Akshay: If ever it was treated as string :wink:

@PikK45: Yes., then fine.., nice prediction :slight_smile: