0

I have written a Bash script which stores the number of records(line count) in a file and File name which is present in the directory in a output.txt file.

The output.txt file is as below.

No.ofRecord    FileName                   delimiter
563394         1--UnixfileName.txt        28
364794         2--UnixfileName.txt        28
785895         3--UnixfileName.txt        28
99778453       1--NextUnixFileName.txt    18
95645453       2--NextUnixFileName.txt    18
99745313       3--NextUnixFileName.txt    18

Required results

output.txt

No.ofRecord    FileName                   delimiter
563394         1--UnixfileName.txt        28
364794         2--UnixfileName.txt        28
785895         3--UnixfileName.txt        28
99778453       1--NextUnixFileName.txt    18
95645453       2--NextUnixFileName.txt    18
99745313       3--NextUnixFileName.txt    18

TOTAL :
1714083  UnixfileName
295169219 NextUnixFileName

Note:

Sum the No.ofRecord if File name like UnixFileName

Sum the No.ofRecord if File name like NextUnixFileName.

Thanks in advance.

Satya
  • 13

1 Answers1

2
$ awk 'NR > 1 { k = substr($2, 4); cnt[k] += $1 } { print } END { print "\nTOTAL:"; for (k in cnt) print cnt[k], k }' file
No.ofRecord    FileName                   delimiter
563394         1--UnixfileName.txt        28
364794         2--UnixfileName.txt        28
785895         3--UnixfileName.txt        28
99778453       1--NextUnixFileName.txt    18
95645453       2--NextUnixFileName.txt    18
99745313       3--NextUnixFileName.txt    18

TOTAL:
1714083 UnixfileName.txt
295169219 NextUnixFileName.txt

The awk script sums up the first column based on a key k which is taken as the second column from its fourth character onwards. This is done for all input line from the file, except the first (which is a header). All input lines are passed on unmodified as output.

At the end, the totals are printed for each found key.

To get the same column width on the totals as for the rest of the data, that last print cnt[k], k may be changed to some variation of

printf("%-15d%s\n", cnt[k], k)

which formats the number as a left-justified, 15 character wide, integer.

Kusalananda
  • 333,661