Replace the first column of a text file to be 6 minus the current value

I have the following file, space separated

2.5   235215           3.1925
3.7   125255           1.3125

I need to change the first column to be 6 minus the current value. The desired result is

3.5   235215           3.1925
2.3   125255           1.3125

How to do this with a Bash script?

I tried

$KMAX=6
sed -E "s/^(([^ ]+ +){3})$1  /1$KMAX-$1 /" $1
Asked By: sunxd

||

The task is solved easily using awk:

awk -v kmax=6 '{$1=kmax-$1}1' file.txt 
  • This will import the value 6 into an awk variable kmax which can then be used internally.
  • The program will replace the first column $1 by the arithmetic result of kmax-$1.
  • The seemingly "stray" 1 outside of the action block results in the current line being printed, including all modifications made.

One caveat: for space-separated columns, awk will only use one space as separator on output, so the result will be in your case:

3.5 235215 3.1925
2.3 125255 1.3125
Answered By: AdminBee

Using Raku (formerly known as Perl_6)

~$ raku -ne 'given .split( / s+ /) { put join "t", (6 - .[0], .[1..*])  };'  

OR:

~$ raku -ne 'given .split( / s+ /) { join("t", (6 - .[0], .[1..*])).put };'  

Raku is a Perl-family programming language. An advantage of using Raku is that it can easily handle one-liners, and if you need to step up to more serious CSV processing, you can use a module (e.g. Text::CSV).

Above the code is invoked with the -ne non-autoprinting, linewise flags. The given keyword tells Raku to treat the input as one item (a line), while splitting on whitespace. Within the block, 6 is subtracted from the .[0] first element, and the result placed in a list with .[1..*] the remaining elements. Finally, the output is printed with put.

Sample Input:

2.5   235215           3.1925
3.7   125255           1.3125

Sample Output:

3.5 235215  3.1925
2.3 125255  1.3125

https://raku.org

Answered By: jubilatious1
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.