2

I want to run all this comands over the same csv file, but I don't know how to make up an awk script to run all these commands and get a new csv file with all the modifications...

The csv file has this strcuture

a,b,c,d,
1,3,4,1
2,2,3,1
...
3,3,1,2

And I want to change all the "3" in the second field for the "w" letter, all the "2" in the second field for the "y" letter and all the 3 in the third field for the "fail" word.

To obtain this output:

a,b,c,d,
1,w,4,1
2,y,fail,1
...
3,w,1,2

The .awk file is:

#! /bin/awk -f


BEGIN { FS = "," }
#{print $1","}
{sub(/3/, "w,", $2)}1
{sub(/2/, "y,", $2)}1
{sub(/3/, "fail,", $3)}1



END{print "acabé"} 

The commands in between are to replace specific numbers of the same field for specific "names" And in the console I am writing:

./name.awk oldfile.csv >newfile.csv
Toto
  • 89,455
  • 62
  • 89
  • 125
Sebastian
  • 55
  • 4

3 Answers3

0

Use

awk '
  BEGIN {FS = OFS = ","}
  $2 == "3" {$2 = "w"}
  $2 == "2" {$2 = "y"}
  $3 == "3" {$3 = "fail"}
  1
' oldfile.csv

Notes:

  • use the OFS variable for the "output field separator"
  • see how 1 in the awk code only appears once? To see why, click on the tag, then click the Learn more… link.
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

With GNU awk for arrays of arrays:

awk '
    BEGIN {
        FS = OFS = ","
        map[2][2] = "y"
        map[2][3] = "w"
        map[3][3] = "fail"
    }
    {
        for (fldNr in map) {
            if ($fldNr in map[fldNr]) {
                $fldNr = map[fldNr][$fldNr]
            }
        }
        print
    }
' file
a,b,c,d,
1,w,4,1
2,y,fail,1
...
3,w,1,2

By the way -

  1. Don't give your executable file names (aka scripts) a suffix like .awk - name all of your software based on what it does, not how it does it, including what language it's written in.
  2. Don't call awk with a shebang, see https://stackoverflow.com/a/61002754/1745001.
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

There are multiple ways to run awk commands:

  • explicitly:

     awk 'your code here' filename ...
    
  • as an executable, shebang-enabled file like the one you provided.

  • code from a file:

     awk -f script.awk filename ...
    
  • using awk's include (which is similar to python's import and C++' include statements). it can also be used to include files within files.

     @include script.awk
    

    More info Include Files (The GNU Awk User’s Guide).

U. Windl
  • 3,480
  • 26
  • 54
msaa
  • 1
  • 1