Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AWK populating an empty column with AWK and Sed is not working

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading