I’m working on a home work assignment. The question is:
Write an
awkscript to select all regular files (not directories or
links) in/etcending with.conf, sort the result by size from
smallest to largest, count the number of files, and print out the
number of files followed by the filenames and sizes in two columns.
Include a header row for the filenames and sizes. Paste both your
script and its output in the answer area.
I’m really struggling trying to get this to work through using awk. Here’s what I came up with.
ls -lrS /etc/*.conf |wc –l
will return the number 33 which is the number of files .conf files in the directory.
ls -lrS /etc/*.conf |awk '{print "File_Size"": " $5 " ""File_Name and Size"": " $9}'
this will make 2 columns with the name and size of the .conf file in the directory.
It works, but I don’t think it is what he’s looking for. I’m having an AWKful time.
Let’s see here…
So far you haven’t addressed this, but if you are piping in the output of
ls -l..., this is easy, select onbecause directories start with
d, symbolic links withland so on. Only plain old files start with-. NowWell, counting matches is easy enough…
To get the filename and size, look at the output of
ls -land count up columnsThe big difficulty here is that
awkdoesn’t provide much by way of sorting primitives, so that’s the hard part. That can be beaten if you want to be clever but it is not particularly efficient (see the awful thing I did in a [code-golf] solution). The easy (and unixy) thing to do would be to pipe part of the output tosort, so…we collect a line for each file into a big stringGives output like
(BTW–There is a
testsubdirectory here, and you’ll note that it does not appear in the output.)