Sourin Biswas
Sourin Biswas

Reputation: 45

How to change value from first line in one newly added column

I have a file named file1.txt where below data is there

APPLICATION ODATE       IF_EXECUTING  APPLICATION_STATUS
Job1        20200731    Post          NOTOK
Job2        20200731    Post          NOTOK
Job3        20200731    Post          NOTOK
JOb3        20200731    Post          NOTOK

Adding one new column using below command.

awk -v column=4 -v value="four" 'BEGIN {FS = OFS = "\t\t\t";}{for ( i = NF + 1; i > column; i-- ) {$i = $(i-1);}$i = value;print $0;}' file1.txt

Output:

APPLICATION ODATE       IF_EXECUTING  APPLICATION_STATUS                      four
Job1        20200731    Post          NOTOK                   four
JOb2        20200731    Post          NOTOK                   four
Job3        20200731    Post          NOTOK                   four
JOb4        20200731    Post          NOTOK                   four

Here adding three "\t" character. First line "four" should be spaced with APPLICATION_STATUS with just one \t and first line "four" should be replaced with "CYCLE_NUMER"

Desired output:

APPLICATION ODATE       IF_EXECUTING  APPLICATION_STATUS    CYCLE_NUMBER
Job1        20200731    Post          NOTOK                 four
JOb2        20200731    Post          NOTOK                 four
Job3        20200731    Post          NOTOK                 four
JOb4        20200731    Post          NOTOK                 four

Upvotes: 2

Views: 73

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133650

Could you please try following, written and tested with shown samples in GNU awk.

awk -v val="four" -v header="CYCLE_NUMBER" '
FNR==1{
  print $0,header
  next
}
{
  print $0,val
}
'  Input_file | column -t

OR as per @Cyrus sir's comment in case you want to do within awk itself then try following.

awk -v val="\t\t\tfour" -v header="\tCYCLE_NUMBER" '
FNR==1{
  print $0,header
  next
}
{
  print $0,val
}
'  Input_file

Explanation: Adding explanation for above code. 2nd solution is also more alike 1st solution only thing 2nd one doesn't have column command in it and TAB printing is getting handled within awk variables itself.

awk -v val="four" -v header="CYCLE_NUMBER" '   ##Starting awk program from here with val value of four and header value of CYCLE_NUMBER here.
FNR==1{                           ##Checking condition if FNR==1 then do following.
  print $0,header                 ##Printing current line and header value here.
  next                            ##next will skip all further statements from here.
}
{
  print $0,val                    ##Printing current line with val here.
}
'  Input_file | column -t         ##Mentioning Input_file name here and sending output of awk command to column command to get it in good manner.

Upvotes: 4

Related Questions