arieffirdaus
arieffirdaus

Reputation: 63

Compare line by line within a linux file

I have a file (test1.txt) like this:

100 100
200 200
300 HR
400 IT
500 500
600 600

And I want to desired output like this:

100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0

I already try to run this command:

#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi

but the result is not as I expected.

Upvotes: 0

Views: 110

Answers (4)

Ivan
Ivan

Reputation: 7257

Awk is quite good but i wonder if sed can do it? So here it is a variant with sed.

sed 's/\(^.*\) \1/& 0/;t;s/$/ 1/' file

Explanation, first command s/\(^.*\) \1/& 0/

  • \(^.*\) - define 1st column
  • \1 - add copy of the 1st column

So we've got a 1st column and a copy of it in a pattern and if patern matched we change it to itself(&) + ' 0' then t will run next s command if firs didn't match. Second command s/$/ 1/ simple add ' 1' to the end of the line.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following.

awk '{$(NF+1)=$1==$2?0:1} 1' Input_file

OR to have output TAB delimited try:

awk 'BEGIN{OFS="\t"} {$(NF+1)=$1==$2?0:1} 1' Input_file

Explanation: Adding detailed explanation for above code.

awk '                   ##Starting awk program from here.
{
  $(NF+1)=$1==$2?0:1    ##Creating a new NF+1 field which will be newer last field and its value will be decided as per condition:
}                       ##If $1 and $2 are equal then set 0 or set 1 its value.
1                       ##1 will print the complete line value here(including new last field value).
' Input_file            ##Mentioning Input_file name here.

Upvotes: 5

David C. Rankin
David C. Rankin

Reputation: 84541

A variation is just to check field equality between $1==$2, and if they are equal, append " 0", otherwise append " 1", e.g.

$ awk '$1==$2{print $0" 0"; next } {print $0" 1"}' file
100 100 0
200 200 0
300 HR 1
400 IT 1
500 500 0
600 600 0

Which can be shortened to awk '{print $0, $1!=$2}' file with a slight loss in readability.

Upvotes: 3

Shawn
Shawn

Reputation: 52344

Another approach:

awk '{ printf "%s\t%s\t%d\n", $1, $2, $1 != $2 }' test1.txt

Upvotes: 2

Related Questions