0

I have a txt file which named as output.txt:

output.txt

2128,4.4
2128,5.5

I wish to have a compare script that first line first number before comma is equal to second line first number, then it will return second line second number after comma.

output:
5.5

If the output.txt have different number for first line first number and second line first number, for example:

output.txt
2622,56
1011,65

Then expected output will be return a stringThe value is different

  • sed -e 's/^(.\{4\}).*/\1/' out.txt but this will print out all line with first 4 integer – Shi Jie Tio Jan 14 at 3:33
  • sed -e 's/,.*//' output.txt and this will print out all the line with the value before comma, I wish to just retrieve first line or second line so that i can make comparison, anyone can share ideas? – Shi Jie Tio Jan 14 at 3:37
2

Confirmed in bash:

#!/bin/bash

file=/path/to/output.txt

if [[ $(awk -F , 'NR==1 {print $1}' $file) -eq $(awk -F , 'NR==2 {print $1}' $file) ]]; then

awk -F , 'NR==2 {print $2}' $file

else

echo "The value is different"

fi

-The variable file is assigned to the path of wherever output.txt is located.

-In the if statement, awk uses , as the delimiter and prints and compares the second values of the second column on each line.

-If the values are equal, then it prints the second column of the second line which is 5.5

-If the values are not equal, then it prints "The value is different".

I tested this with two files with the values that you specified. You can change the value of the file variable in the script to work with others.

4

You can handle this with an AWK script:

#!/usr/bin/awk -f
BEGIN { FS = "," }
NR == 1 { value = $1 }
NR == 2 {
    if ($1 == value) print $2
    else print "The value is different"
    exit
}

This stores the first value on the first line, then compares that to the first value on the second line, and prints the second value if they’re equal, or “The value is different” otherwise. It then exits explicitly, to avoid spending time reading any further lines.

1

I Tried with sed and awk command

#!/bin/bash
i=`sed -n '1p' l.txt| awk -F "," '{print $1}'`
j=`sed -n '2p' l.txt| awk -F "," '{print $1}'`
if [[ $i == $j ]]
then
awk -F "," 'NR==2{print $2}' l.txt
else
echo "The value is different"
fi

output

5.5
0

Normally sed operates on a per line basis. We can override this and stuff the next line into the pattern space for inspection.

Once we make sure that the first fields of the two lines in the pattern space are same, we do the substitution and head for the exit. OTW, the complete pattern space is overhauled with the desired message and then sed prints it as a default action.

sed -e '
   N
   s/^\([^,]*\),.*\n\1,\(.*\)/\2/;t
   s/.*/The Value is Different/
'  file.csv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.