Bash字符串处理(与Java对照) - 4.字符串输出

Bash字符串处理(与Java对照) - 4.字符串输出

In Java

输出到标准输出设备(控制台、屏幕)

System.out.println(s);

输出到标准错误设备(控制台、屏幕)

System.err.println(s);

输出到文件

PrintWriter outputStream = new PrintWriter(new FileWriter("output_file.txt"));

try {

    outputStream.println(s);

} finally {  // 别忘记将输出流关闭,否则会造成资源泄漏

    outputStream.close();

}

Line-Oriented I/O (来自 http://download.oracle.com/javase/tutorial/essential/io/charstreams.html)

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;

public class CopyLines {
    public static void main(String[] args) throws IOException {
        BufferedReader inputStream = null;
        PrintWriter outputStream = null;

        try {
            inputStream = 
                new BufferedReader(new FileReader("xanadu.txt"));
            outputStream = 
                new PrintWriter(new FileWriter("characteroutput.txt"));

            String l;
            while ((l = inputStream.readLine()) != null) {
                outputStream.println(l);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}
 

In Bash

echo

关于echo命令,也可以参考“我使用过的Linux命令之echo - 显示文本、打印信息 ”。

输出字符串常量

示例:echo Hello

示例:echo "Hello"

[root@jfht tmp]# echo Hello
Hello
[root@jfht tmp]# echo "Hello"
Hello
[root@jfht tmp]# echo Hello   World
Hello World
[root@jfht tmp]# echo "Hello   World"
Hello   World
[root@jfht tmp]#

输出变量

格式1:echo $VAR

格式2:echo ${VAR}

上面的格式,如果变量VAR保存的字符串中包含空格、换行,那么这些空格、跳格、换行将会被压缩掉。

格式3:echo "$VAR"

格式4:echo "${VAR}"

注意,不能用单引号来引用。

[root@jfht tmp]# VAR=" Hello    World   "
[root@jfht tmp]# echo $VAR
Hello World
[root@jfht tmp]# echo ${VAR}
Hello World
[root@jfht tmp]# echo "$VAR"
 Hello    World  
[root@jfht tmp]# echo "${VAR}"
 Hello    World  
[root@jfht tmp]# echo '$VAR'
$VAR
[root@jfht tmp]# echo $'$VAR'
$VAR
[root@jfht tmp]#

注意:echo在输出信息的时候会自动加上换行,

如果不需要换行,加上 -n参数即可

man echo 写道
-n do not output the trailing newline

[root@jfht tmp]# echo "Hello"
Hello
[root@jfht tmp]# echo -n "Hello"
Hello[root@jfht tmp]#

echo -e 命令参数中的转义字符

man echo 写道
       -e enable interpretation of backslash escapes

       If -e is in effect, the following sequences are recognized:

       \0NNN  the character whose ASCII code is NNN (octal)
       \\     backslash
       \a     alert (BEL)
       \b     backspace
       \c     suppress trailing newline
       \f     form feed
       \n     new line
       \r     carriage return
       \t     horizontal tab
       \v     vertical tab

       NOTE: your shell may have its own version of echo, which usually supersedes the version described here.  Please
       refer to your shell’s documentation for details about the options it supports.
 

\"  双引号 gives the quote its literal meaning
\$  美元符 gives the dollar sign its literal meaning (variable name following \$ will not be referenced)
\\  反斜杠、转义符本身 gives the backslash its literal meaning

\` 反引号

\<newline> 就是\跟上换行,那么换行的作用不再有,只起到续行的作用。

\n  换行 means newline
\r  回车 means return
\t  制表符,跳格 means tab
\v  竖制表符 means vertical tab
\b  退格 means backspace
\a  警报 means alert (beep or flash)
\0xx  八进制表示的ASCII码字符 translates to the octal ASCII equivalent of 0nn, where nn is a string of digits

[root@jfht ~]# echo -e '\n'


[root@jfht ~]# echo -e 'a\tb'
a       b
[root@jfht ~]#

输出命令执行结果

格式1:command line

就是直接执行命令,当然可以

格式2:echo `command line`

格式3:echo $(command line)

这两种格式的执行效果是一样的,都会把命令输出的前后空格去掉、中间的空格换行压缩为一个空格。

格式2:echo "$(command line)"

格式3:echo "`command line`"

这两种格式的执行效果也是一样的,并且会保持命令输出的空格和换行。一般与直接执行命令的输出一致。

[root@jfht tmp]# ls
ct08  ct08.min.tar.gz  ls0.txt  ls1.txt  ls2.txt
[root@jfht tmp]# echo `ls`
ct08 ct08.min.tar.gz ls0.txt ls1.txt ls2.txt
[root@jfht tmp]# echo $(ls)
ct08 ct08.min.tar.gz ls0.txt ls1.txt ls2.txt
[root@jfht tmp]# echo "`ls`"
ct08
ct08.min.tar.gz
ls0.txt
ls1.txt
ls2.txt
[root@jfht tmp]# echo "$(ls)"
ct08
ct08.min.tar.gz
ls0.txt
ls1.txt
ls2.txt
[root@jfht tmp]#

问题来了:为什么 echo "`ls`" 和 echo "$(ls)" 的输出结果与 直接执行 ls 不一致呢?可以看看下面的解释:

如果标准输出是终端,那么是显示为多列形式的;否则就是一行一列。而对于$(ls)和`ls`,实际上标准输出已经不是终端了。

info ls 写道
By default, the output is sorted alphabetically, according to the
locale settings in effect.(1) If standard output is a terminal, the
output is in columns (sorted vertically) and control characters are
output as question marks; otherwise, the output is listed one per line
and control characters are output as-is.
 

输出到文件(标准输出重定向)

覆盖原来的文件

格式:echo "$S" >output.txt

追加到文件

格式:echo "$S" >>output.txt

[root@jfht tmp]# S=123456789
[root@jfht tmp]# echo "$S" >output.txt 
[root@jfht tmp]# cat output.txt
123456789
[root@jfht tmp]# echo "$S" >output.txt
[root@jfht tmp]# cat output.txt      
123456789
[root@jfht tmp]# echo "$S" >>output.txt
[root@jfht tmp]# cat output.txt       
123456789
123456789
[root@jfht tmp]#

输出到标准错误设备

比如用来打印程序的出错信息

echo "$S" >&2

>&2表示把标准输出重定向到文件描述符2,而这正是标准错误输出的文件描述符。

[root@jfht tmp]# if ! ls "*"; then echo "error ls" >&2; fi
ls: *: 没有那个文件或目录
error ls
[root@jfht tmp]#

上面命令行的意思是说列出文件名为*的文件,如果出错,就打印错误信息。

输出到别的进程

管道线(|)

示例:echo "$S" | wc -c

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.
 

Here Document方式

示例:wc -c <<EOF

$S

EOF

Advanced Bash-Scripting Guide: Chapter 19. Here Documents 写道
A here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command, such as ftp, cat, or the ex text editor.

COMMAND <<InputComesFromHERE
...
...
...
InputComesFromHERE

A here document supports parameter and command substitution. It is therefore possible to pass different parameters to the body of the here document, changing its output accordingly.
 

Here String方式

示例:wc -c <<<"$S"

Advanced Bash-Scripting Guide: 19.1. Here Strings 写道
A here string can be considered as a stripped-down form of a here document.
It consists of nothing more than COMMAND <<< $WORD,
where $WORD is expanded and fed to the stdin of COMMAND.
 

[root@jfht tmp]# S=123456789
[root@jfht tmp]# echo "$S" | wc -c
10
[root@jfht tmp]# wc -c <<<"$S"
10
[root@jfht tmp]# wc -c <<EOF
> $S
> EOF
10
[root@jfht tmp]#

格式化输出(printf)

printf "%8s" "$S"

类似C语言的格式化输出,此处不深入探讨。将在本系列的第18节详述。

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

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

上节内容:Bash字符串处理(与Java对照) - 3.给(字符串)变量赋值

下节内容:Bash字符串处理(与Java对照) - 5.字符串输入(读取字符串)

猜你喜欢

转载自codingstandards.iteye.com/blog/1168164