`

Bash字符串处理(与Java对照) - 18.格式化字符串

阅读更多

Bash字符串处理(与Java对照) - 18.格式化字符串

In Java

class Formatter

参见:http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax

 

String.format

static String     format(String format, Object... args)
          使用指定的格式字符串和参数返回一个格式化字符串。

 

 

参见:String.format函数使用方法介绍 http://blog.csdn.net/andycpp/article/details/1749700

 

System.out.printf

参见:http://www.java2s.com/Code/JavaAPI/java.lang/System.out.printf.htm

 

1.  System.out.printf('%b', String str )
2.  System.out.printf('%c', char ch )
3.  System.out.printf('%03d', int i )
4.  System.out.printf('%e', float )
5.  System.out.printf('%03f', float f)
6.  System.out.printf('%.2f', float f )
7.  System.out.printf('{%07.3f}', float f )
8.  System.out.printf('%f', float f )
9.  System.out.printf('%g', float f )
10.  System.out.printf('%h', float f )
11.  System.out.printf('%s', 5)
12.  System.out.printf('%s://%s/%s\n', String str1, String str2, String str3)
13.  System.out.printf('%1 s...', String str )
14.  System.out.printf('%5s', String str)
15.  System.out.printf('%-5s', String str) (2)
16.  System.out.printf( '%-10.10s %s', String word, int length )
17.  System.out.printf('%.5s', String str) (3)
18.  System.out.printf('%s', Date date )
19.  System.out.printf('%tc', Date date ) (lowercase t, lowercase c)
20.  System.out.printf('%tC', Date date ) (lowercase t, uppercase C)
21.  System.out.printf('%tD', Date date )
22.  System.out.printf('%tF', Date date )
23.  System.out.printf('%tr', Date date )
24.  System.out.printf('%tR',Date date )
25.  System.out.printf('%tT', Date date )
26.  System.out.printf('%tz', Date date )
27.  System.out.printf('%Tc', Date date ) (Uppercase T, lowercase c)
28.  System.out.printf('%1x, %1X', 0xCAFE )
29.  System.out.printf( Locale.CHINA, '%tc', Date date )
30.  System.out.printf( Locale.ITALIAN, '%tc', Date date )

 

In Bash

printf

man bash 写道
printf [-v var] format [arguments]
Write the formatted arguments to the standard output under the control of the format. The format is a
character string which contains three types of objects: plain characters, which are simply copied to
standard output, character escape sequences, which are converted and copied to the standard output, and
format specifications, each of which causes printing of the next successive argument. In addition to
the standard printf(1) formats, %b causes printf to expand backslash escape sequences in the correspond-
ing argument (except that \c terminates output, backslashes in \', \", and \? are not removed, and octal
escapes beginning with \0 may contain up to four digits), and %q causes printf to output the correspond-
ing argument in a format that can be reused as shell input.

The -v option causes the output to be assigned to the variable var rather than being printed to the
standard output.

The format is reused as necessary to consume all of the arguments. If the format requires more argu-
ments than are supplied, the extra format specifications behave as if a zero value or null string, as
appropriate, had been supplied. The return value is zero on success, non-zero on failure.
 
man 1 printf 写道
FORMAT controls the output as in C printf. Interpreted sequences are:

转义字符:
\" double quote
\NNN character with octal value NNN (1 to 3 digits)
\\ backslash
\a alert (BEL)
\b backspace
\c produce no further output
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\xHH byte with hexadecimal value HH (1 to 2 digits)
\uHHHH Unicode (ISO/IEC 10646) character with hex value HHHH (4 digits)
\UHHHHHHHH Unicode character with hex value HHHHHHHH (8 digits)

%% a single %
%b ARGUMENT as a string with ‘\’ escapes interpreted,

except that octal escapes are of the form \0 or \0NNN

and all C format specifications ending with one of diouxXfeEgGcs, with ARGUMENTs converted to proper type
first. Variable widths are handled.

 

如果你想对printf命令更深入的了解,参见 http://wiki.bash-hackers.org/commands/builtin/printf

 

打印换行

示例来自 http://ss64.com/bash/printf.html

 # Use \n to start a new line
$ printf "Two separate\nlines\n"         
Two separate
lines

 

[root@jfht ~]# printf "Two separate\nlines\n"
Two separate
lines
[root@jfht ~]# echo "Two separate\nlines\n"     
Two separate\nlines\n
[root@jfht ~]# echo -e "Two separate\nlines\n"
Two separate
lines

[root@jfht ~]# echo -n -e "Two separate\nlines\n"
Two separate
lines
[root@jfht ~]#

用0填充(Zero Padding)

技巧来自 Zero Padding in Bash  http://jonathanwagner.net/2007/04/zero-padding-in-bash/

创建从1到31为名的目录

for ((x=1;x<=31;x+=1)); do mkdir $x; done

一位数字前面加0

for ((x=1;x< =31;x+=1)); do mkdir `printf "%02d" $x`; done

 

例子来自 http://ss64.com/bash/printf.html

# Echo a list of numbers from 1 to 100, adding 3 digits of Zero padding
# so they appear as 001, 002, 003 etc:
$ for ((num=1;num<=100;num+=1)); do echo `printf "%03d" $num`; done

 

设置打印宽度、用空白填充

示例来自 http://linuxconfig.org/bash-printf-syntax-basics-with-examples

 

#/bin/bash

divider===============================
divider=$divider$divider

header="\n %-10s %8s %10s %11s\n"
format=" %-10s %08d %10s %11.2f\n"

width=43

printf "$header" "ITEM NAME" "ITEM ID" "COLOR" "PRICE"

printf "%$width.${width}s\n" "$divider"

printf "$format" \
Triangle 13  red 20 \
Oval 204449 "dark blue" 65.656 \
Square 3145 orange .7
 

[root@jfht ~]# ./table.sh
 Triangle   00000013        red       20.00
 Oval       00204449  dark blue       65.66
 Square     00003145     orange        0.70
[root@jfht ~]#

 

 

本文链接:http://codingstandards.iteye.com/blog/1198098   (转载请注明出处)

返回目录:Java程序员的Bash实用指南系列之字符串处理(目录) 

上节内容:Bash字符串处理(与Java对照) - 17.判断是否以另外的字符串结尾

下节内容:Bash字符串处理(与Java对照) - 19.查找字符的位置

 

3
1
分享到:
评论

相关推荐

    Advanced Bash-Scripting Guide <>

    9.2. 操作字符串 9.3. 参数替换 9.4. 指定类型的变量:declare 或者typeset 9.5. 变量的间接引用 9.6. $RANDOM: 产生随机整数 9.7. 双圆括号结构 10. 循环和分支 10.1. 循环 10.2. 嵌套循环 10.3. 循环控制 10.4. ...

    Linux高级bash编程

    使用模式匹配来分析比较特殊的字符串 9-20. 对字符串的前缀或后缀使用匹配模式 9-21. 使用declare来指定变量的类型 9-22. 间接引用 9-23. 传递一个间接引用给awk 9-24. 产生随机数 9-25. 从一副扑克牌中取出一张...

    Linux简明教程.rar

    4.查找字符串 5.显示文件头部 6.显示文件尾部 7.忽略文件中的重复行 8.比较两个文件 9.按顺序显示文件内容 三、进程间通信命令----------------------------------------------------------------------------...

    sh:具有bash支持的shell解析器,格式化程序和解释器; 包括shfmt

    有关诸如对字符串执行shell扩展之类的高级操作,请参见。 shfmt GO111MODULE=on go get mvdan.cc/sh/v3/cmd/shfmt shfmt格式化外壳程序。 请参阅以快速了解其默认样式。 例如: shfmt -l -wscript.sh 有关更多...

    Shell解析器,格式化程序和解释器(sh / bash / mksh),包括shfmt-Golang开发

    有关诸如对字符串执行shell扩展之类的高级操作,请参见shell示例。 shfmt GO111MODULE =运行时获取mvdan.cc/sh/v3/cmd/shfmt shfmt格式的shell程序。 它可以使用制表符或任意数量的空格缩进。 请参阅canonical.sh以...

    宋劲彬的嵌入式C语言一站式编程

    1.1. 初始化字符串 1.2. 取字符串的长度 1.3. 拷贝字符串 1.4. 连接字符串 1.5. 比较字符串 1.6. 搜索字符串 1.7. 分割字符串 2. 标准I/O库函数 2.1. 文件的基本概念 2.2. fopen/fclose 2.3. stdin/stdout/stderr ...

    2009 达内Unix学习笔记

    /字符串 从上往下查找匹配的字符串; ?字符串 从下往上查找匹配的字符串; n 继续查找。 四、退出命令 exit 退出; DOS内部命令 用于退出当前的命令处理器(COMMAND.COM) 恢复前一个命令处理器。 Ctrl+d 跟exit...

    入门学习Linux常用必会60个命令实例详解doc/txt

    last login:Tue ,Nov 18 10:00:55 on vc/1 上面显示的是登录星期、月、日、时间和使用的虚拟控制台。 4.应用技巧 Linux 是一个真正的多用户操作系统,可以同时接受多个用户登录,还允许一个用户进行多次登录。这...

    cmd操作命令和linux命令大全收集

    start 程序名或命令 /max 或/min 新开一个新窗口并最大化(最小化)运行某程序或命令 mem 查看cpu使用情况 attrib 文件名(目录名) 查看某文件(目录)的属性 attrib 文件名 -A -R -S -H 或 +A +R +S +H 去掉...

    output-formatter:Annotateprefix 命令输出

    输出格式化程序 注释/前缀命令输出。 仅适用于安装了 bash 的计算机。 安装 在 Mac 上,您可以执行以下操作: brew install ...

    fmt:一个字符串格式化模块,用于在Oberon-7中使用INTEGER和REAL值

    一个实验性的Oberon-7模块,提供INTEGER和REAL值的格式功能。 它受KarlLandström的OBNC oberon编译器及其扩展库的启发。 安装 先决条件 该存储库假定您已安装的编译器v0.16.1或更高版本。 假定您已配置了有效的C...

    实战Linux Shell编程与服务器管理-作者:卧龙小三(1)

    Chapter 6 变量与字符串操作 Chapter 7 高级变量 Chapter 8 算术运算 Chapter 9 流程控制 Chapter 10 函数 Chapter 11 转向 Chapter 12 trap——陷阱触发 Chapter 14 进程管理和工作控制 Chapter 15 历史...

    linux.chm文档

    useradd -c "Name Surname " -g admin -d /home/user1 -s /bin/bash user1 创建一个属于 "admin" 用户组的用户 useradd user1 创建一个新用户 userdel -r user1 删除一个用户 ( '-r' 排除主目录) usermod -c ...

    实战Linux Shell编程与服务器管理-作者:卧龙小三(7)

    Chapter 6 变量与字符串操作 Chapter 7 高级变量 Chapter 8 算术运算 Chapter 9 流程控制 Chapter 10 函数 Chapter 11 转向 Chapter 12 trap——陷阱触发 Chapter 14 进程管理和工作控制 Chapter 15 历史...

    RED HAT LINUX 6大全

    本书全面系统地介绍了Red Hat Linux 6。全书共分为五个部分,包括35章和四个...14.9.18 load printers=(G) 257 14.9.19 null passwords=(G) 257 14.9.20 password level和username level(G) 257 14.9.21 security=(G...

    JSON.awk:用AWK编写的实用JSON解析器

    (awk)挂接到解析器并输出事件实用回调(可选) 捕获无效的JSON输入以进行进一步处理选择MIT或Apache 2许可证兼容JSON.sh(自2013-03-13起)默认输出格式非功能转换输入值,例如字符串/数字归一化与Awk实现的兼容性...

    机器学习大作业基于python开发的恶意加密流量检测软件源码(含说明文档).zip

    脚本去除了不合规则的数据行,并且将时间字符串转换为了时间戳格式。 使用方法 ```bash python3 csv2libsvm.py input_file output_file 79 其中79是label的列号(第80列) ``` analyse_dataset.py 用于分析、...

    ARM_Linux启动分析.pdf

    id一般要求4个字符以内,对于getty或其他login程序项,要求id与tty的编号相同,否则getty程序将不能正常工作。 runlevel 是init所处于的运行级别的标识,一般使用0-6以及S或s。0、1、6运行级别被系统保留,0作为...

Global site tag (gtag.js) - Google Analytics