bash之printf printf 16进制输出

前几天看到一篇英文的关于bash的printf使用方法,觉得不错,简单的翻译了一下


-----这里讲的printf指的是bash的内建命令(bash-builtin),而不是C函数中的printf(),不过它所实现的功能和printf()函数是非常类似的,可以说是echo命令的一个继承和发展,更加接近POSIX标准。

-----使用语法:
  1. printf
复制代码先举个例子:
  1. SURNAME=china
  2. LASTNAME=unix
  3. printf "Surname: %snName:%sn" "$SURNAME" "$LASTNAME"
  4. Surname: china
  5. Name: unix
复制代码如果你想把输出作为一个变量,也很简单,只要使用–v var的形式就可以。
  1. printf -v var"%sxxx"
  2. echo $var
  3. xxx
复制代码-----FORMAT部分内容很多放到后,先说下ARGUMENTS,

一般情况下,ARGUMENT是一个字符(STRING),当然也可以是数值(字),不过有特定的格式,如下(为了尊重原“注”,这里给出英文注释):
Number-FormatDescription
NA normal decimal number
0NAn octal number
0xNA hexadecimal number
0XNA hexadecimal number
"X(a literal double-quote infront of a character): interpreted asnumber (underlying codeset)don't forgetescaping
'X(a literal single-quote infront of a character): interpreted asnumber (underlying codeset)don't forgetescaping


<1>如果FORMATspecifies少于ARGUMENTS的个数时,printf会按照设定好的格式,把所有的ARGUMENTS格式化输出。
例子:
  1. printf "%s#%s|n" "xxx""yyy" "zzz" "ttt" "vvv"
  2. xxx#yyy|
  3. zzz#ttt|
  4. vvv#|
复制代码<2>如果FORMANTspecifies多于ARGUMENTS的个数时,如果FORMAT是数值(字)格式,则按0处理,如果ARUGENT是字符格式,则按NULL处理。
例子:
  1. printf "%s#d#%sn""xxx"
  2. xxx#0000#
复制代码<3>如果FORMAT是数值(字)格式时,需要注意,数字要满足八进制的要求(base8),因为printf命令会按照bash的数字规则来处理。
例子:
  1. printf "%dn""01"
  2. 1

  3. printf "%dn""08"
  4. -bash: printf: 08: invalidnumber
  5. 0
复制代码-----下面开始说FORMAT部分。

Printf对FORMAT的解释方法实质上和C函数的printf是一样的,它所识别的字符只有“diouxXfeEgGcs”,使用方法就百分号加上这些字符,”%+字符”。如果要打印百分号符,也很简单,double下,”%%”。
对以上“%+字符”的解释如下:

FormatDescription
%bPrint the associated argument while interpreting backslash escapesin there
%qPrint the associated argumentshell-quoted,reusable as input
%dPrint the associated argument assigneddecimalnumber
%iSame as %d
%oPrint the associated argument asunsignedoctalnumber
%uPrint the associated argument asunsigneddecimalnumber
%xPrint the associated argument asunsignedhexadecimalnumber with lower-casehex-digits (a-f)
%XSame as %x, but with upper-case hex-digits (A-F)
%fInterpret and print the associated argumentasfloatingpointnumber
%eInterpret the associated argument asdouble, and printit in ±e format
%ESame as %e, but with an upper-case E in the printed format
%gInterprets the associated argument asdouble, butprints it like %f or %e
%GSame as %g, but print it like %E
%cInterprets the associated argument as character: only the firstcharacter of a given argument is printed
%sInterprets the associated argument literally as string
%bInterprets the associated argument as a string and interpretingescape sequences in it
%qPrints the associated argument in a format, that it can be re-usedas shell-input (escaped spaces etc..)
%nNo conversion or printing is done. Assigns the number of so farprinted characters to the variable named in the correspondingargument (similat to C's printf)
%(FORMAT)Toutput the date-time string resulting from using FORMAT as a formatstring for strftime(3). The associated argument is the number ofseconds since Epoch, or -1 (current time) or -2 (shell startuptime)
%%No conversion is done. Produces a % (percent sign)


既然说printf,在功能上,是echo的继承和发展,那它就一定有更加flexible的设计,下面我们来例举一下。
<1> Modifiers (不知怎么翻译好)
bash之printf printf 16进制输出
先看个例子吧:
  1. printf "Psn" "This fieldis 50 characters wide..."
  2. This fieldis 50 characters wide...
复制代码这个例子中的”50”就是一个Modifier,可以实现向左对齐,字符宽度50,这也是我们最为常见的一种文本输出需求。

下面让我们看看,还有什么其他的Modifiers:

Field outputformat

Anynumber: Specifies aminimum fieldwidth, if the text to print is smaller, it's padded withspaces, if the text is bigger, the field is expanded

.

Thedot: Together with a field width, the fieldisnotexpandedwhen the text is bigger, the text is cutted instead. "%.s" is anundocumented equivalent for "%.0s", which will force a field widthof zero, effectively hiding the field from output

*

Theasterisk: the width is given as argument before the stringor number. Usage (the "*" corresponds to the "20"): printf "%*sn"20 "test string"

#

"Alternative format" for numbers: see table below

-

Left-boundtextprinting in the field (standard isright-bound)

0

Pads numbers with zeros, not spaces

Pad a positive number with a space, where a minus (-) is fornegative numbers

+

Prints all numberssigned(+for positive, - for negative)


AlternativeFormat
%#oThe octal number is printed with a leading zero, unless it's zeroitself
%#x, %#XThe hex number is printed with a leading "0x"/"0X", unless it'szero
%#g, %#GThe float number is printed withtrailingzerosuntil the number of digits for thecurrent precision is reached (usually trailing zeros are notprinted)
all number formats except %d, %o, %x, %XAlways print a decimal point in the output, even if no digitsfollow it


此外,精度(precision)也是常见的输出要求,格式为”.”,部分可以是具体的数字,也是”*”;如果是后者,写法上少有差异:
  1. printf "%.*fn" 104
  2. 4.0000000000
  3. printf "%.10fn"4
  4. 4.0000000000
复制代码<如果是字符串的话,DIGIT定义的是最大的field width, 如果是整数,则是数字输出的个数,不足是有”0”补齐>

下面是一些逃逸字符(Escape codes)的写法:

CodeDescription
\Prints the character (backslash)
aPrints the alert character (ASCII code 7 decimal)
bPrints a backspace
fPrints a form-feed
nPrints a newline
rPrints a carriage-return
tPrints a horizontal tabulator
vPrints a vertical tabulator
"Prints a '
?Prints a ?
Interprets asoctalnumberand prints the corresponding character from the character set
same as
xInterprets ashexadecimalnumberand prints the corresponding character from the character set(3digits)
usame as x, but4 digits
Usame as x, but8 digits


-----最后列举一些例子,加深理解!

1. 打印十六进制值:
  1. printf "%dn"0x41
  2. 65
  3. printf "%dn"-0x41
  4. -65
  5. printf "%+dn" 0x41 #输出数值为”+”时,不能用printf "%dn" +0x41的写法。
  6. +65
复制代码2.打印十进制值:
  1. printf "%on" 65
  2. 101
  3. printf "on" 65
  4. 00101
复制代码3.如果打印”0”呢?
  1. printf "%dn"
  2. 0
复制代码4.打印字符代码(两种方式):
  1. printf "%dn" 'A
  2. 65
  3. printf "%dn""'A"
  4. 65
复制代码5.Code表的打印:
  1. for ((x=0; x <= 127;x++)); do
  2. printf '= | o | 0xxn' "$x""$x" "$x"
  3. done
复制代码6.巧妙打印n个”-"
  1. length=40
  2. printf -v line '%*s'"$length"
  3. echo ${line// /-}
  4. ----------------------------------------
复制代码或者:
  1. length=40
  2. eval printf -v line '%.0s-'{1..$length}
  3. ----------------------------------------
复制代码7.原文中还提到了一种替代Date的方法:"%(...)T"(不过我没有运行成功,不知什么原因,大家试试)
  1. printf 'This is week%(%U/%Y)T.n' -1
  2. This is week 52/2010.
复制代码

  

爱华网本文地址 » http://www.413yy.cn/a/25101010/28510.html

更多阅读

二进制数与十六进制数之间如何互相转换 二进制转换十六进制

二进制数与十六进制数之间如何互相转换——简介二进制与十六进制之间的转换与二进制和八进制之间的转换很类似,今天我们来详细看一下:首先,我们来看一下数学关系即24=16,即用四位二进制表示一位八进制。二进制数与十六进制数之间如何互

声明:《bash之printf printf 16进制输出》为网友浊酒倾觞分享!如侵犯到您的合法权益请联系我们删除