返回列表 发帖
本帖最后由 newswan 于 2024-7-19 00:22 编辑

假如知道最大宽度是10
awk '{ printf "%-10s %-10s %-10s\n", $1, $2, $3 }' a.txtCOPY

TOP

本帖最后由 newswan 于 2024-7-19 14:32 编辑

1 字体的宽度,夹杂中文,更纱一个字体,能完全对齐
2 中文的宽度,上面的所有方案,都没有计算中文宽度,用制表符处理误差,一旦前面中文过多,也不能对齐。

TOP

本帖最后由 newswan 于 2024-7-20 01:54 编辑

保存为 a.awk ,然后 awk -f a.awk a.txt
BEGIN {
FS = " "
while ( getline < ARGV[1] ) {
for (i = 1; i <= NF; i++) {
if ( length($i) > maxlen[i] ) {
maxlen[i] = length($i)
}
}
}
}
{
for (i = 1; i <= NF; i++) {
printf "%-*s\t",maxlen[i],$i
}
printf "\r\n"
}COPY
1

评分人数

TOP

powershell
$file = Get-Content -Path "data.txt" -Encoding UTF8
$maxlen = @(0) *10
$file | ForEach-Object {
$arr = $_  -split "\s+"
for ( $i =0 ; $i -lt $arr.count ; $i++ ){
if ( $maxlen[$i] -lt ($arr[$i]).length ) {
$maxlen[$i] = ($arr[$i]).length
}
}
}
$maxlen = $maxlen -join " " -replace "( 0)*" -split "\s+"
$file | ForEach-Object {
$arr = $_  -split "\s+"
$str = ""
for ( $i =0 ; $i -lt $arr.count ; $i++ ){
$str += ($arr[$i]).PadRight($maxlen[$i]," ") + "  "
}
write-host ( $str -replace "\s$","" )
}COPY

TOP

本帖最后由 newswan 于 2024-7-21 15:54 编辑

回复 29# 娜美

前面发的都没计算全角字符
#36 #37  计算了全角,用 ":" 分隔字段

TOP

本帖最后由 newswan 于 2024-7-21 20:35 编辑

支持全角字符
awk -f format-table.awk data.txt
function getWidth(str,LenStr,LenASC,LenHZ) {
LenStr = length(str)
LenASC = gsub( /[\x00-\x7F]/ , "" , str )
LenHZ = length(str) / length("一")
return  LenASC + LenHZ * 2
}
function getLengthHZ(str,LenHZ) {
gsub( /[\x00-\x7F]/ , "" , str )
LenHZ = length(str) / length("一")
return  LenHZ
}
BEGIN {
FS = " "
while ( getline < ARGV[1] ) {
for (i = 1; i <= NF; i++) {
len = getWidth($i)
if ( len > maxWidth[i] ) {
maxWidth[i] = len
}
}
}
# print "--maxWidth--"
# for ( i in maxWidth ) {
# printf "%4s" , maxWidth[i]
# }
# printf "\r\n"
# print "----"
}
{
for (i = 1; i <= NF; i++) {
LenHZ = getLengthHZ($i)
printf "%-*s:" , maxWidth[i] + LenHZ , $i
}
printf "\r\n"
}COPY
注意 第 35 行 由于 awk 环境不同,可能是 "+ LenHZ" 可能是 "- LenHZ"

TOP

本帖最后由 newswan 于 2024-7-21 19:56 编辑

支持全角字符
format-table.ps1 "in.txt" "out.txt"
param(
[String]$filenameIn ,
[String]$filenameOut
)
$file = Get-Content -Path $filenameIn -Encoding UTF8
$maxWidth = @{}
$file | ForEach-Object {
$arr = $_  -split "\s+"
for ( $i = 0 ; $i -lt $arr.count ; $i++ ){
$Width = ($arr[$i]).length + ( $arr[$i] -replace "[\x00-\x7F]","" ).length
if ( $maxWidth[$i] -lt $Width ) {
$maxWidth[$i] = $Width
}
}
}
$strTable = [System.Collections.ArrayList]@()
$file | ForEach-Object {
$arr = $_  -split "\s+"
$str = ""
for ( $i = 0 ; $i -lt $arr.count ; $i++ ){
$LenHZ = ( $arr[$i] -replace "[\x00-\x7F]","" ).length
$str += ($arr[$i]).PadRight( $maxWidth[$i] - $LenHZ , " " ) + ":"
}
[void]$strTable.add( $str ) #$str -replace "\s$",""
}
$strTable | Out-File -Encoding 'UTF8' -FilePath $filenameOutCOPY

TOP

回复 40# buyiyang


对,由于 awk 使用环境不同,有的地方是 + 有的地方是 -

TOP

本帖最后由 newswan 于 2024-7-21 20:05 编辑

回复 42# 娜美

#36 #37 输出正确
输出到屏幕正确,保存到文件也应该正确,文件不能对齐,是因为编辑器的字体问题

TOP

返回列表