在第9个排序序号的前面加空格



我有以下文件和代码

file.txt
field1      or      field1
field2              field2
.                   .
.                   .
.                   .
field13             field8
field14             field9
awk '
function ordinal(i,   mod, str) {
mod = i%10
str = i
if (i~/1[1-3]$/)  # for numbers ending in 11, 12, 13
str = str "th"
else if (mod==1)
str = str "st"
else if (mod==2)
str = str "nd"
else if (mod==3)
str = str "rd"
else
str = str "th"
return str
}
{ print ordinal(++i)")"" value : " $1}' file.txt

当字段大于10时,我如何在序号1-9中添加空格,而当字段小于10时,如何在序号1-9中添加空格以使列对齐

所需结果为以下

1st) value : field1    or      1st) value : field1
2nd) value : field2            2nd) value : field2
.                               .
.                               .
.                               .
13th) value : field13           8th) value : field8
14th) value : field14           9th) value : field9

您可以将前9条记录存储在一个数组中。当你到达第十条记录时,你会填充存储的记录:

awk '
function header(i, s, m) {
if ( i ~/1[1-3]$/) { s = "th" }
else {
m = i % 10
if (m == 1) { s = "st" }
else if (m == 2) { s = "nd" }
else if (m == 3) { s = "rd" }
else { s = "th" }
}
return i s ") value :" 
}
NR < 10 { prev[NR] = $0 }
NR == 10 {
for (i = 1; i < NR; i++) {
print " " header(i), prev[i]
}
}
NR >= 10 { print header(NR), $0 }
END{
if (NR-1 < 10) {
for (i = 1; i < NR; i++) {
print header(i), prev[i]
}
}
}
' file.txt

将awk的输出管道传输到column命令

awk '
function ordinal(i,   mod, str) {
mod = i%10
str = i
if (i~/1[1-3]$/)  # for numbers ending in 11, 12, 13
str = str "th"
else if (mod==1)
str = str "st"
else if (mod==2)
str = str "nd"
else if (mod==3)
str = str "rd"
else
str = str "th"
return str
}
{ print ordinal(++i)")"" value : " $1}' file.txt | column -t

相关内容

最新更新