使用printf格式化输出:截断或填充 [英] Formatting output with printf: truncating or padding
问题描述
我想产生以下输出:
> Avril Stewart 99 54
> Sally Kinghorn 170 60
> John Young 195 120
> Yutte Schim... 250 40
如您所见,少于14个字符的名称用空格填充.长度超过15个字符的名称将被截断:"Yutte Schimmelpenninck"将截断为"Yutte Schim ...".
As you can see, names shorter than 14 characters are padded with spaces. Names longer than 15 characters are truncated: 'Yutte Schimmelpenninck' truncates to 'Yutte Schim...'.
这是我尝试实现的目标(变量$name
,$height
和$weight
是从文件中提取的,并且循环在每个文件数据上运行printf
命令):
Here is what I have tried to achieve this (the variables $name
, $height
, and $weight
are extracted from files, and a loop runs the printf
command on each file data):
printf '%-14s -%3s -%3s\n' "$name" "$height" "$weight"
> Avril Stewart 99 54
> Sally Kinghorn 170 60
> John Young 195 120
> Yutte Schimmelpenninck 250 40
printf
单线是理想的解决方案.
A printf
one-liner is the desired solution.
什么代码将产生第一块输出?
What code will produce the first block of output?
推荐答案
在printf
命令之前,您要检查名称是否长于14个字符,如果是,则截断该名称并将其后三个字符替换为点.这个命令可以做到:
Before your printf
command, you want to check if a name is longer than 14 characters, and if yes, truncate it and replace the last three characters with dots. This command does that:
(( ${#name} > 14 )) && name="${name:0:11}..."
它将name
替换为前11个字符,并附加...
.
It replaces name
with its first eleven characters and appends ...
.
您还必须修复printf
格式字符串:而不是
You also have to fix the printf
format string: instead of
'%-14s -%3s -%3s\n'
必须是
'%-14s %-3s -%-3s\n'
或者您得到诸如
Avril Stewart - 99 - 54
不过,也许这只是一个错字,因为示例输出中没有连字符.
Maybe that was just a typo, though, as your example output didn't have the hyphens.
总共:
$ name='Avril Stewart'; weight=99; height=54
$ (( ${#name} > 14 )) && name="${name:0:11}..."
$ printf '%-14s %-3s %-3s\n' "$name" $weight $height
Avril Stewart 99 54
$ name='Sally Kinghorn'; weight=170; height=60
$ (( ${#name} > 14 )) && name="${name:0:11}..."
$ printf '%-14s %-3s %-3s\n' "$name" $weight $height
Sally Kinghorn 170 60
$ name='Yutte Schimmelpeninck'; weight=250; height=40
$ (( ${#name} > 14 )) && name="${name:0:11}..."
$ printf '%-14s %-3s %-3s\n' "$name" $weight $height
Yutte Schim... 250 40
因此,如果您从文件中读取此内容(例如,逗号分隔),则会遇到如下所示的循环:
So if you read this from a file, for example comma separated, you'd end up with a loop like this:
while IFS=, read -r name weight height; do
(( ${#name} > 14 )) && name="${name:0:11}..."
printf '%-14s %-3s %-3s\n' "$name" $weight $height
done < inputFile
导致
Avril Stewart 99 54
Sally Kinghorn 170 60
John Young 195 120
Yutte Schim... 250 40
我认为不可能一口气.我尝试了三元运算符,并尝试了类似的方法
I don't think it's possible in a one-liner. I experimented with the ternary operator and tried something like
printf '%s\n' $(( ${#name} > 14 ? "${name:0:11}..." : "$name" ))
但是这里的问题是它仅适用于整数,并且字符串在算术上下文中扩展为零.
but the problem here is that it only works for integers, and strings expand to zero in arithmetic context.
这篇关于使用printf格式化输出:截断或填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!