`

Bash字符串处理(与Java对照) - 5.字符串输入(读取字符串)

阅读更多

Bash字符串处理(与Java对照) - 5.字符串输入(读取字符串)

In Java

Scanner类:Scanner.hasNext() & Scanner.next() & Scanner.hasNextLine() & Scanner.nextLine()

JavaDoc class Scanner 写道
A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

A scanning operation may block waiting for input.

The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
 

下面是关于 Scanner.hasNext() 和 Scanner.next() 的例子,用于读取以空白分隔的标识符。

Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
   String msg = scanner.next();
   System.out.println(msg);
}

 

下面是关于 Scanner.hasNextLine() 和 Scanner.nextLine() 的例子,用于读取输入数据行。

Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
   String msg = scanner.nextLine();
   System.out.println(msg);
}

 

更详细的说明请参考:http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

 

Console类:System.console() & Console.readLine() & Console.readPassword()

Console类是JDK6加入的,它是对控制台的封装。使用 System.console() 可以获得与当前Java虚拟机关联的控制台,如果有的话。Console.readLine可以读取一行,Console.readPassword可以读取密码。

 

JavaDoc class Console 写道
public final class Console
extends Object
implements Flushable

Methods to access the character-based console device, if any, associated with the current Java virtual machine.

Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method. If no console device is available then an invocation of that method will return null.

 String     readLine()
          Reads a single line of text from the console.

 char[]     readPassword()
          Reads a password or passphrase from the console with echoing disabled
 

下面是一个关于Console的示例代码:

 

        Console console = System.console(); // 获得Console实例对象     
        if (console != null) {              // 判断是否有控制台的使用权     
            String user = new String(console.readLine("Enter username:"));      // 读取整行字符     
            String pwd = new String(console.readPassword("Enter passowrd:"));   // 读取密码,输入时不显示     
            console.printf("Username is: " + user + "\n");      // 显示用户名     
            console.printf("Password is: " + pwd + "\n");   // 显示密码     
        } else {     
            System.out.println("Console is unavailable.");  // 提示无控制台使用权限     
        }
 

更详细的说明请参考:·http://download.oracle.com/javase/6/docs/api/java/io/Console.html

 

In Bash

从标准输入读取

使用read命令读取字符串到变量中。但是,如果有反斜杠,将起到转义的作用。\\表示一个\号,\<newline>表示续行,\<char>代表<char>本身。

格式:read VAR

格式:read -p <prompt> VAR

 

[root@node56 ~]# read VAR
hello world
[root@node56 ~]# echo $VAR
hello world
[root@node56 ~]# read -p "Input your number: " VAR
Input your number: 123
[root@node56 ~]# echo $VAR
123
[root@node56 ~]# read VAR
yes\tno
[root@node56 ~]# echo $VAR
yestno
[root@node56 ~]#

 

 

读取一行文本,但是取消反斜杠的转义作用。

格式:read -r VAR

格式:read -p <prompt> -r VAR

man bash: read 写道
-r Backslash does not act as an escape character. The backslash is considered to be part of the
line. In particular, a backslash-newline pair may not be used as a line continuation.

 

[root@node56 ~]# read -r VAR
yes\tno
[root@node56 ~]# echo $VAR 
yes\tno
[root@node56 ~]#

 

关于read -p

此参数用于在读取变量之前显示提示信息。如果输入重定向了,就不会显示,比如重定向从文件中读取。

也就是说,read -p PROMPT VAR 不等同于 echo PROMPT; read VAR 的组合。

man bash: read 写道
-p prompt
Display prompt on standard error, without a trailing newline, before attempting to read any
input. The prompt is displayed only if input is coming from a terminal.

 

读取密码(输入的字符不回显)

格式:read -s PASSWORD

格式:read -p <prompt> -s PASSWORD

man bash: read 写道
-s Silent mode. If input is coming from a terminal, characters are not echoed.
 

[root@node56 ~]# echo $PASSWORD

[root@node56 ~]# read -s PASSWORD
[root@node56 ~]# echo $PASSWORD 
12345

[root@node56 ~]# read -p "Input password: " -s PASSWORD
Input password:
[root@node56 ~]# echo $PASSWORD 

54321

 

读取指定数量字符

格式:read -n <nchars> VAR

格式:read -p <prompt> -n <nchars> VAR

man bash: read 写道
-n nchars
read returns after reading nchars characters rather than waiting for a complete line of input.
 

[root@node56 ~]# read -p "Input two chars: " -n 2 VAR
Input two chars: 12 [root@node56 ~]# echo $VAR
12
[root@node56 ~]#

 

在指定时间内读取

格式:read -t <seconds> VAR

格式:read -p <prompt> -t <seconds> VAR

 

man bash: read 写道
-t timeout
Cause read to time out and return failure if a complete line of input is not read within timeout
seconds. This option has no effect if read is not reading input from the terminal or a pipe.
 

[root@node56 ~]# read -p "Input some words in 5 seconds: " -t 5 VAR
Input some words in 5 seconds: [root@node56 ~]#

 

从文件中读取

格式:read VAR <file.txt

对于read命令,可以指定-r参数,避免\转义。

格式:read -r VAR <file.txt

错误:cat file.txt | read VAR    (此处read命令将会在子进程中执行,子进程无法更改父进程的变量)

 

[root@web ~]# cat input.txt
Some text here
with backslash \ here
dollar $HOME meet

[root@web ~]# cat input.txt | read VAR
[root@web ~]# echo $VAR

[root@web ~]# read VAR <input.txt
[root@web ~]# echo $VAR
Some text here
[root@web ~]# read VAR1 VAR2 VAR3 VAR4<input.txt
[root@web ~]# echo "VAR1=$VAR1 VAR2=$VAR2 VAR3=$VAR3 VAR4=$VAR4"
VAR1=Some VAR2=text VAR3=here VAR4=

[root@web ~]# read VAR1 VAR2<input.txt
[root@web ~]# echo "VAR1=$VAR1 VAR2=$VAR2"
VAR1=Some VAR2=text here
[root@web ~]#

上面的直接对read命令输入重定向,只能读取输入文件中的一行。

 

如果需要读取整个文件,最好将其写在一个代码块中。

Advanced Bash-Scripting Guide: Chapter 3. Special Characters {} 写道
Block of code [curly brackets]. Also referred to as an inline group, this construct, in effect, creates an anonymous function (a function without a name). However, unlike in a "standard" function, the variables inside a code block remain visible to the remainder of the script.

The code block enclosed in braces may have I/O redirected to and from it.

Unlike a command group within (parentheses), as above, a code block enclosed by {braces} will not normally launch a subshell.
 

 

{ read LINE1; read LINE2; read LINE3; } <input.txt

注意每个read命令之后都要以分号结束。

 

[root@web ~]# { read LINE1; read LINE2; read LINE3; } <input.txt
[root@web ~]# echo $LINE1
Some text here
[root@web ~]# echo $LINE2
with backslash here
[root@web ~]# echo $LINE3
dollar $HOME meet
[root@web ~]#

上面LINE2中\ 没有读取出来,因为在没有加上-r参数时,read会转义。

 

现在加上-r参数来测试一下。

{ read -r LINE1; read -r LINE2; read -r LINE3; } <input.txt

 

[root@web ~]# { read -r LINE1; read -r LINE2; read -r LINE3; } <input.txt
[root@web ~]# echo $LINE1
Some text here
[root@web ~]# echo $LINE2
with backslash \ here
[root@web ~]# echo $LINE3
dollar $HOME meet
[root@web ~]#

 

从Here Document读取

错误:read VAR <<EOF

some string

EOF

正确:{ read VAR; } <<EOF

some string

EOF

问题:为什么写在代码块中才能读取呢?

 

[root@web ~]# read VAR <<EOF
> some string
> EOF
[root@web ~]# echo "$VAR"

[root@web ~]# { read VAR; } <<EOF
> hello
> EOF
[root@web ~]# echo "$VAR"        
hello
[root@web ~]#

 

从Here String读取

read VAR <<< "some string"

read VAR <<< "$STR"

 

[root@web ~]# read VAR <<< "some string"
[root@web ~]# echo $VAR
some string
[root@web ~]#

 

 

补充:关于 cat input.txt | read VAR 的问题

先说一下我对管道线的理解:管道线两侧的命令,前一个命令的输出(标准输出),将作为后一个命令的输入(标准输入)。两侧的命令都是在子进程中执行的,都有各自独立的地址空间,子进程会继承(复制)父进程所有的环境变量。子Shell(subshell)是一种特殊的子进程,它会继承(复制)父Shell的所有变量;对于非子Shell进程(外部命令),只有环境变量会被继承(复制)。但是,子进程一旦启动,它所有的变量只在它的进程空间中有效,它对变量的修改都是对自己范围之内的变量的修改,对父进程相同名称的变量是没有影响的。而子进程启动之后,它的父进程对父进程变量的修改,对子进程相同名称的变量也是没有影响的。

Advanced Bash-Scripting Guide: Chapter 3. Special Characters | 写道
|

pipe. Passes the output (stdout) of a previous command to the input (stdin) of the next one, or to the shell. This is a method of chaining commands together.

A pipe, as a classic method of interprocess communication, sends the stdout of one process to the stdin of another. In a typical case, a command, such as cat or echo, pipes a stream of data to a filter, a command that transforms its input for processing.

The output of a command or commands may be piped to a script.

A pipe runs as a child process, and therefore cannot alter script variables.

variable="initial_value"
echo "new_value" | read variable
echo "variable = $variable" # variable = initial_value
 

[root@web ~]# cat input.txt
Some text here
with backslash \ here
dollar $HOME meet

[root@web ~]# cat input.txt | read VAR
[root@web ~]# echo $VAR

 

上面的cat input.txt的输出将作为read VAR的输入。
[root@web ~]# cat input.txt | { read VAR; echo $VAR; }
Some text here

可以看到管道线后面的子Shell中确实读到了值。
[root@web ~]# echo $VAR

 

但父Shell中的相同变量不会改变。
[root@web ~]#

 

 

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

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

上节内容:Bash字符串处理(与Java对照) - 4.字符串输出

下节内容:Bash字符串处理(与Java对照) - 6.判断字符串是否为空(不为空)

 

 

5
3
分享到:
评论
4 楼 superlittlefish 2011-09-14  
codingstandards 写道
superlittlefish 写道
(此处read命令将会在子进程中执行,子进程无法更改父进程的变量) 不明白为什么会子进程无法更改父进程的变量 ?

做了一下补充,看看能否说明问题

3ks , 理解了.
3 楼 codingstandards 2011-09-14  
superlittlefish 写道
(此处read命令将会在子进程中执行,子进程无法更改父进程的变量) 不明白为什么会子进程无法更改父进程的变量 ?

做了一下补充,看看能否说明问题
2 楼 superlittlefish 2011-09-13  
(此处read命令将会在子进程中执行,子进程无法更改父进程的变量) 不明白为什么会子进程无法更改父进程的变量 ?
1 楼 山风小子 2011-09-13  
不错,很详细!

相关推荐

    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.按顺序显示文件内容 三、进程间通信命令----------------------------------------------------------------------------...

    2009 达内Unix学习笔记

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

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

    这是因为Linux和许多版本的Unix一样,提供了虚拟控制台的访问方式,允许用户在同一时间从控制台(系统的控制台是与系统直接相连的监视器和键盘)进行多次登录。每个虚拟控制台可以看作是一个独立的工作站,工作台...

    安卓系统下的bash shell,ssh服务器,gcc编译器以及vim文本编辑器等

    如果给出的字符串不能作为唯一标识,则bash不予补全;再次敲击TAB键,bash会给出参考列表;如果参考列表中的内容过多,bash会询问是否显示该列表;根据提供的参数路径来进行补全,如果参数没有任何提示信息,则默认...

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

    5. logoff---------注销命令 6. shutdown-------60秒倒计时关机命令 7. lusrmgr.msc----本机用户和组 8. services.msc---本地服务设置 9. oobe/msoobe /a----检查XP是否激活 10. notepad--------打开记事本 11...

    cpp-utilities:我的应用程序使用的常见C ++类和例程,例如参数解析器,IO和转换实用程序

    没有多个堆分配的构建字符串(“字符串生成器”) 使用标准IO流 读取/写入各种大小的原始数据类型(little-endian和big-endian) 读/写终止的字符串和大小前缀的字符串 读取/写入INI文件 按位读取

    linux.chm文档

    hdparm -tT /dev/sda 在磁盘上执行测试性读取操作 cat /proc/cpuinfo 显示CPU info的信息 cat /proc/interrupts 显示中断 cat /proc/meminfo 校验内存使用 cat /proc/swaps 显示哪些swap被使用 cat /proc/...

    weather:一个bash脚本,报告瑞典机场的天气

    #Function脚本将机场作为输入参数,然后从aro.lfv.se读取METAR字符串。 METAR字符串看起来像ESMS 230950Z 17009KT CAVOK 16/14 Q1013 ,它是非常隐秘的,这就是存在此脚本的原因。 机场工作人员每小时(或在较小的...

    Shell脚本学习笔记

    3.2.2字符串比较 64 3.2.3 文件比较 65 3.2.4 复合条件检查 65 3.3 if-then的高级特征与case命令 66 3.3.1 使用双圆括号 66 3.3.2 使用双方括号 67 3.3.3 case命令 67 3.4 for命令 67 3.4.1 读取列表 68 3.4.2 读取...

    kallisto-nf:Kallisto和Sleuth RNA-Seq工具的nextflow实现

    Kallisto-NF Kallisto和Sleuth RNA-...)指定多个文件,在这种情况下,请确保参数字符串值用单引号引起来(请参见下面的示例) 它必须以.fastq 。 参与的任务:Kallisto映射。 默认情况下,它设置为Kallisto-NF的位

    cpfb:Bash 的配置解析器

    cpfb Bash 的配置解析器 什么? cpfb 的重点是提供一个可由 bash 解析的配置语法,它直接映射到有用的 bash 结构。 它应该阅读基础知识: 标准键/值对,用 bash 编写为MyVar=... 键/值对块使用 '::' 字符串定义。 他

    shell脚本命令行参数简介

    之所以用到命令行参数,关键在于shell脚本需要与运行脚本的人员进行交互。...同时输入多个参数可以是数值也可以是字符串)时,必须使用空格分隔要想在参数值中包含空格,就必须使用单引号或双引号)当参数多于9个后,

    WINCVS和CVSNT安装包

    例如:对于关键字 Revision,如果检入前字符串是 $Revision: 1.1 $,则生成的字串与以前相同而不会是 $Revision: 5.7 $。 -kb(替换过程中阻止换行转换) 类似 -ko 选项,并阻止换行字符的转换,这种转换是因为换...

    DataScienceBabyNames

    您可以通过字符串数组ARGS访问命令行参数。 参见这篇文章使用Julia ZipFile.jl 库扫描输入压缩文件。 这个示例也可能有用。使用SQlite.jl 库与SQLite3交互。 您可以在这里找到一些文档使用SQLite.jl创建BabyNames表...

    win7 超级终端

    windows 7 超级终端是一款通用的串行交互软件,很多嵌入式应用的系统有与之交换的相应程序,通过这些程序,可以通过超 级终端与嵌入式系统交互,使超级终端成为嵌入式系统的“显示器”。 windows 7 超级终端 特色...

    ARM_Linux启动分析.pdf

    提取并分析核心启动参数(从环境变量中读取参数,设置相应标志位等待处理,(parse_options()) 控制台初始化(为输出信息而先于PCI初始化,console_init()) 剖析器数据结构初始化(prof_buffer和prof_len变量) ...

    regextester:一个CLI工具,用于使用各种正则表达式样式(bre,ere,pcre等)测试正则表达式(regex)

    RegexTester模板 一个用于使用各种正则表达式语言测试正则表达式(regex)的CLI工具。 目录 安装/设置 ... regext从stdin读取测试字符串,因此您可以| 来自echo或cat管子。 范例1: echo " abcd

Global site tag (gtag.js) - Google Analytics