I'm new here and I want to ask how to add sizes of files with the same name? My file names are actually different from each other but I cut them so I could get files that are grouped together.
here are my original files with sizes (sample)
sample.txt has this data inside:
Now I cut the filenames inside sample.txt to remove those characters starting from '_' (underscore). They become like this:
Now I want to add sizes of all files with same filename as seen above. Output should be like this:
Please help. Thanks a lot guys. I'm stuck here for hours now
Assuming there are no line numbers in sample.txt
:
cut -f 1 -d _ sample.txt | awk '{a[$2] += $1} END{for (i in a) print a[i], i}'
You may want to add | sort -k 2
at the end.
EDIT1 - explanation as requested:
The cut
command cuts every line with _
delimiter and saves the first part only. You have already done it with your original file.
Then the awk
command finds two fields in every line. We call them size and name, but awk
refers to them as $1
and $2
internally. For every line it increments one element of an array a
(the name a
is arbitrarily chosen and has nothing to do with filename in the sample). The name $2
tells which element to increment -- it is an index; the size $1
is the incrementation value. awk
is smart enough to initialize a
element with 0
as it is mentioned for the first time. The particular element is incremented every time its index (name) appears as a second field of the input line. At the end (after the last line of the input) awk
goes through every known index of a
and prints the value (which is now cumulative size) and an index (name).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments