加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 用于选择文件和打印文件大小的Awk脚本

发布时间:2020-12-14 01:03:38 所属栏目:Linux 来源:网络整理
导读:我正在做家务工作.问题是: Write an awk script to select all regular files (not directories or links) in /etc ending with .conf ,sort the result by size from smallest to largest,count the number of files,and print out the number of files fo
我正在做家务工作.问题是:

Write an awk script to select all regular files (not directories or
links) in /etc ending 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.

我真的在努力通过使用awk来努力工作.这就是我想出来的.

ls -lrS /etc/*.conf |wc –l

将返回数字33,即目录中的.conf文件数.

ls -lrS /etc/*.conf |awk '{print "File_Size"": " $5 "   ""File_Name and Size"": " $9}'

这将使2列具有目录中.conf文件的名称和大小.

它有效,但我不认为这是他正在寻找的.我有一个愉快的时间.

解决方法

我们在这看……

select all regular files (not directories or links)

到目前为止,你还没有解决这个问题,但如果你在ls -l …的输出中输入,这很容易,请选择

/^-/

因为目录以d开头,符号链接以l开头,依此类推.只有普通旧文件以 – 开头.现在

print out the number of files followed

好吧,计算比赛很容易……

BEGIN{count=0}  # This is not *necessary*,but I tend to put it in for clarity
/^-/ {count++;}

要获取文件名和大小,请查看ls -l的输出并计算列数

BEGIN{count=0}
/^-/ {
  count++;
  SIZE=$5;
  FNAME=$9;
}

这里最大的困难是awk没有通过排序原语提供太多,所以这是困难的部分.如果你想要聪明但不是特别有效,那就可以打败(看看我在a [code-golf] solution所做的糟糕事情).容易(和unixy)做的事情是管道输出的一部分进行排序,所以…我们为每个文件收集一行到一个大字符串

BEGIN{count=0}
/^-/ {
  count++
  SIZE=$5;
  FNAME=$9;
  OUTPUT=sprintf("%10dt%sn%s",SIZE,FNAME,OUTPUT);
}
END{
   printf("%d filesn",count);
   printf("  SIZE    tFILENAME"); # No newline here because OUTPUT has it
   print OUTPUT|"sort -n --key=1";
}

给出类似的输出

11 files
  SIZE          FILENAME
       673      makefile
      2192      houghdata.cc
      2749      houghdata.hh
      6236      testhough.cc
      8751      fasthough.hh
     11886      fasthough.cc
     19270      HoughData.png
     60036      houghdata.o
    104680      testhough
    150292      testhough.o
    168588      fasthough.o

(顺便说一句 – 这里有一个测试子目录,你会注意到它没有出现在输出中.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读