1

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.

Christian Hick
  • 401
  • 3
  • 10

2 Answers2

2
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

Cyrus
  • 84,225
  • 14
  • 89
  • 153
0

To answer the question 'why this does not work", you should test the components of your pipeline one by one.

awk -F '\t' '$4 < 0 {print $1}' stack1.txt

prints four empty lines, one for every line with negative column 4 of the original file. Nothing can xargs and sed do with this output to get the effect you want. The input for xargs sed -i ... must be a list of files. The whole attempt is unfortunate.

See Cyrus answer for an alternative, or

perl -i.bak -aple 's/^/c/ if $F[-1]<0' stack1.txt

which works with arbitrary mix of tabs and spaces as separators.

sizif
  • 174
  • 5