Wednesday, April 6, 2022

[SOLVED] AWK populating an empty column with AWK and Sed is not working

Issue

I have the following file called stack1.txt:

        Date    Item    Amount
        2020-01-23      Petrol  -160
        2020-03-24      Electricity     -200
        2020-04-24      Electricity     -200
        2020-05-30      Trim line       -50
        2021-03-11      Martha Burns    150
        2021-03-14      Highbury shops  300

I created an empty column at $1 that I wish to populate so the negative amounts in column $4 get a "c" in column $1, such as

        Date    Item    Amount
c       2020-01-23      Petrol  -160
c       2020-03-24      Electricity     -200
c       2020-04-24      Electricity     -200
c       2020-05-30      Trim line       -50
        2021-03-11      Martha Burns    150
        2021-03-14      Highbury shops  300

I have tried the following command:

awk -F '\t' '$4 < 0 {print $1}' stack1.txt | xargs -r sed -i 's//c/g'

If I cat stack1.txt I still get an unchanged table as above. Originally I used xargs without -r and got sed: no input files. -r removed this. I also tried 's/""/c/g'. I am trying to save the altered output back to stack1.txt hence sed -i. I am however at a loss why this does not work. Appreciate some help on this.


Solution

awk 'BEGIN{ FS=OFS="\t" } $4<0{ $1="c" }1' file

Output:

        Date    Item    Amount
c       2020-01-23      Petrol  -160
c       2020-03-24      Electricity     -200
c       2020-04-24      Electricity     -200
c       2020-05-30      Trim line       -50
        2021-03-11      Martha Burns    150
        2021-03-14      Highbury shops  300

See: Save modifications in place with awk



Answered By - Cyrus
Answer Checked By - Timothy Miller (WPSolving Admin)