固定宽度的制表输出 5


在一个固定宽度和对齐格式中,显示输出多行文本,要求每一列的输出必选具有固定的宽度。格式化操作符可以设置固定宽度输出。

下面的例子通过DIR返回个目录的中的文件列表,然后通过循环输出,文件名和文件大小,因为文件的名字和大小都是不确定的,长度不一样,所以结果拥挤粗糙,可读性差。

PS > dir | ForEach-Object { "$($_.name) = $($_.Length) Bytes" }
.android =  Bytes
.VirtualBox =  Bytes
CMB =  Bytes
Contacts =  Bytes
Desktop =  Bytes
Documents =  Bytes
Downloads =  Bytes
Favorites =  Bytes
funshion =  Bytes
Links =  Bytes
Podcasts =  Bytes
Roaming =  Bytes
Saved Games =  Bytes
Searches =  Bytes
SkyDrive =  Bytes
Tracing =  Bytes
Virtual Machines =  Bytes
VirtualBox VMs =  Bytes
a = 12022 Bytes
a.csv = 986 Bytes
a.ps1 = 18 Bytes
a.txt = 946 Bytes
funshion.ini = 6798 Bytes
PUTTY.RND = 600 Bytes

下面固定列宽的结果,就显得可读性强了。要设置列宽可以将一个逗号放置在通配符与列宽编号的中间,负数设置右对齐,正数设置左对齐。

PS> dir | ForEach-Object { "{0,-20} = {1,10} Bytes" -f $_.name, $_.Length }
Virtual Machines     =            Bytes
VirtualBox VMs       =            Bytes
a                    =      12022 Bytes
a.csv                =        986 Bytes
a.ps1                =         18 Bytes
a.txt                =        946 Bytes
funshion.ini         =       6798 Bytes
PUTTY.RND            =        600 Bytes
.....

引用链接:outputting values in tabular form fixed width

本文链接: https://www.pstips.net/outputting-values-in-tabular-form-fixed-width.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

回复 大胖鱼 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

5 条评论 “固定宽度的制表输出