I have the following file and code
file.txt
field1 or field1
field2 field2
. .
. .
. .
field13 field8
field14 field9
awk '
function ordinal(i, mod, str) {
mod = i
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
How can I add a space to ordinal numbers 1-9 when the fields is more than 10 and not when is less so that the columns are aligned
Τhe desired result is the following
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
CodePudding user response:
Pipe the output of awk to the column
command
awk '
function ordinal(i, mod, str) {
mod = i
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
CodePudding user response:
You can store the first 9 records in an array. When you reach the tenth record then you pad the stored records:
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 = NR }
NR == 10 {
for (i = 1; i < NR; i ) {
print " " header(i), prev[i]
}
nr = 0
}
NR >= 10 { print header(NR), $0 }
END{
if (nr < 10) {
for (i = 1; i <= nr; i ) {
print header(i), prev[i]
}
}
}
' file.txt