-1

I have a kind of the following tsv file:

Hi 10 6
hello 7 1
Hi 6 2

Hence, the related output should be:

Hi 10 6 4
hello 7 1 6
Hi 6 2 4

I'd like to create a 4th column with the difference between the 2 columns $2 and $3, but in an absolute value.

I am trying with the following line, but with no right result:

awk -F\t '{print $0 OFS $2-$3}' file

How can I do? Marco

Marco
  • 27
  • 5
  • 1
    Does this answer your question? [Absolute value in awk doesn't work?](https://stackoverflow.com/questions/11184915/absolute-value-in-awk-doesnt-work); see the various answers for a few ideas on how to implement `abs()` functionality – markp-fuso Jun 17 '22 at 15:50
  • Please provide desired output – Daweo Jun 17 '22 at 15:50

1 Answers1

1

When you write -F\t without quotes you're inviting the shell to interpret the string and so the shell will read the backslash and leave you with -Ft. In some awks -Ft means "use a tab as the separator" while in others it means "use the character t as the separator". I assume since you say your file is a TSV that you want it to use tabs so just write your code to not invite the shell to interpret it, i.e. -F'\t' instead of -F\t.

After that to get the absolute value is obvious and well-covered in many postings:

$ awk 'BEGIN{FS=OFS="\t"} {print $0, ($2>$3 ? $2-$3 : $3-$2)}' file
Hi  10  6   4
hello   7   1   6
Hi  6   2   4

I changed from using -F'\t' to FS="\t" because both FS and OFS need to be set to "\t" and so setting them both together to the same character instead of separately avoids duplication.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185