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

From: http://codingstandards.iteye.com/blog/1198098

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/bashdivider===============================
divider=$divider$dividerheader="\n %-10s %8s %10s %11s\n"
format=" %-10s %08d %10s %11.2f\n"width=43printf "$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

[zcm@bash #86]$./a.shITEM NAME   ITEM ID      COLOR       PRICE
===========================================Triangle   00000013        red       20.00Oval       00204449  dark blue       65.66Square     00003145     orange        0.70
[zcm@bash #87]$



本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/406600.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity基础知识学习笔记二

1&#xff0c;object Instantiate(object original,Vector3 position,Quaternion rotation) 克隆原始物体&#xff0c;并返回克隆物体。例如&#xff1a;Instantiate(prefab,new Vector3(1,1,1),Qutaternion.identity);克隆一个prefab物体。2,InputManager,输入管理器&#xff…

JavaScript 监听手机端的touch滑动事件(滑动手势)

如何监听移动端滑动手势&#xff08;上 / 下 / 左 / 右滑动&#xff09;&#xff0c;今天记录下。 var startx, starty;//获得角度 function getAngle(angx, angy) {return Math.atan2(angy, angx) * 180 / Math.PI; };//根据起点终点返回方向 1向上滑动 2向下滑动 3向左滑动 …

雅虎衰落源于公司领袖缺乏远见与决断个性

文/ 周鸿祎雅虎的衰落&#xff0c;公司领袖负有不可推卸的责任&#xff0c;杨致远缺乏做出决断的个性和能力。 与充满商业智慧的微软和Google相比&#xff0c;雅虎显得太过幼稚。我之前创立的3721卖给了雅虎&#xff0c;后来还有过一段合作&#xff0c;所以对它有较深入的了解。…

java的Random类详解

Random类是一个专门用来生成一个伪随机数的类&#xff0c;这个类提供了两个构造函数&#xff0c;一个使用默认的种子&#xff0c;另一个需要程序员显示传入一个long型整数的种子。与Math类中的random方法生成的伪随机数不同的是&#xff0c;Math的random方法生成的伪随机数取值…

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

From: http://codingstandards.iteye.com/blog/1198917 In Java String.indexOf & String.lastIndexOf int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。 int indexOf(int ch, int fromIndex) 从指定的索引开始搜索&#x…

mint-ui 写一个下拉滑动选择,mt-popup和mt-picker结合使用

<template><div id"feedback"><div click"getpopupVisible">产品选择</div><mt-popupv-model"popupVisible"popup-transition"popup-fade"position"bottom"><div class"picker-toolb…

够学习一辈子的生活经典

说话要用脑子&#xff0c;敏事慎言&#xff0c;话多无益&#xff0c;嘴只是一件扬声器而已&#xff0c;平时一定要注意监督、控制好调频旋钮和音控开关&#xff0c;否则会给自己带来许多麻烦。讲话不要只顾一时痛快、信口开河&#xff0c;以为人家给你笑脸就是欣赏&#xff0c;…

设计模式之单一职责原则

超前的设计或者过度的设计都不是良好的设计&#xff0c;很多时候我们等到代码在第一次变化的时候可以及时作出反应。 What 就一个类&#xff08;接口、结构体、方法等等&#xff09;而言&#xff0c;应该仅有一个引起它变化的原因。 Why 软件设计真正要做的许多内容&#xff0c…

makefile常用语法讲解(1)

From: http://www.cnblogs.com/mydomain/archive/2011/08/12/2136083.html 1、make是一个解释makefile中指令的命令工具。Make工具最主要也是最基本的功能就是通过makefile文件来描述源程序之间的相互关系并自动维护编译工作。而makefile 文件需要按照某种语法进行编写&#…

HTML5如何控制暂停播放停止

本篇教程探讨了HTML5如何控制暂停播放停止&#xff0c;希望阅读本篇文章以后大家有所收获&#xff0c;帮助大家HTML5CSS3从入门到精通 。 <!DOCTYPE HTML> <html> <head> <meta charset"utf-8"> <meta name"viewport" content…

Oracle 高水位(HWM: High Water Mark) 说明

一. 准备知识&#xff1a;ORACLE的逻辑存储管理. ORACLE在逻辑存储上分4个粒度: 表空间, 段, 区 和 块. 1.1 块: 是粒度最小的存储单位,现在标准的块大小是8K,ORACLE每一次I/O操作也是按块来操作的,也就是说当ORACLE从数据文件读数据时,是读取多少个块,而不是多少行. 每一个B…

React开发(153):ant design自定义列

<Row gutter{12}><Col span{12}><Form.Item label"省/市/区"><CascaderfieldNames{fieldNames}options{options}onChange{() > {this.onChange();}}placeholder"请输入"/></Form.Item></Col>

[转]那些年我还不懂:IList,ICollection,IEnumerable,IEnumerator,IQueryable

1、首先看一个简单的例子 int[] myArray { 1, 32, 43, 343 };IEnumerator myie myArray.GetEnumerator();myie.Reset();while (myie.MoveNext()){int i (int)myie.Current;Console.WriteLine("Value: {0}", i);} 相信很多人都不会像上面这样去遍历myArray这个数组…

makefile常用讲解(2)

From: http://www.cnblogs.com/mydomain/archive/2011/08/12/2136085.html 4&#xff09;变量的引入 变量的引入和应用&#xff1a; CCgcc HD-I headers SC-c $< OBJ-o $ bin/st_work : obj/main.o obj/st_work.o obj/fun.o gcc $^ -o $ (命令一定要用以Tab…

router-link

组件的属性有&#xff1a; to 、replace、 append、 tag、 active-class、 exact 、 event、 exact-active-class to&#xff08;必选参数&#xff09;&#xff1a;类型string/location 表示目标路由的链接&#xff0c;该值可以是一个字符串&#xff0c;也可以是动态绑定的描…

Qt编程'hello world

#include<QApplication>#include<QLabel>int main(int argc,char*argv[]){QApplicatin app(argc,argv);QLabel *label("hello");label->show();return app.exec()} 编译运行&#xff1a; qmake -project 生成 .pro文件qmake 生成 makemake执行 转载于…

电子工程师必上的十大专业网站

这是很久以前看过的帖子&#xff0c;感觉非常不错&#xff0c;今天特地找出来&#xff0c;便于自己以后经常翻阅&#xff01;&#xff01;今天再看这篇文章&#xff0c;发现很多网站自己还是没有账号&#xff0c;原来自己还是非常的不进取啊。来源&#xff1a;hi.baidu.com 作者…