例如printf的在bash不会创建一个新行 [英] Printf example in bash does not create a newline

查看:131
本文介绍了例如printf的在bash不会创建一个新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的printf 在bash脚本工作,后加入无空格\\ n不会创建一个换行符,而加空格创建一个换行符,即摹:


  1. 后没有空格\\ n

      NEWLINE =`printf的\\ n`
    回声-eFIRSTLINE $ {}换行符lastLine所

    结果:

      FirstlineLastline


  2. 在太空\\ n

      NEWLINE =`printf的\\ n`
    回声-eFIRSTLINE $ {}换行符lastLine所

    结果:

      FIRSTLINE
     lastLine所


问题:为什么没有1.创建以下结果:

  FIRSTLINE
lastLine所

我知道这个具体问题可能已被周围使用其他技术工作,但我想集中1.为什么不工作。

编辑:
当代替了printf使用回声,我得到预期的结果,但为什么printf的工作方式不同?

  NEWLINE =`回声\\ n`
    回声-eFIRSTLINE $ {}换行符lastLine所

结果:

  FIRSTLINE
    lastLine所


解决方案

倒引号操作者除去尾随新行。请参阅 3.4.5。命令替换是在 http://tldp.org/LDP/ Bash的初学者,指南/ HTML / sect_03_04.html

上编辑的问题

注意

比较:

  [阿尔瓦罗@本地〜] $ printf的\\ n[阿尔瓦罗@本地〜] $回声\\ n
\\ n
[阿尔瓦罗@本地〜] $回声-e\\ n
[阿尔瓦罗@本地〜] $

echo命令不会将 \\ n 作为新行,除非你告诉他这样做的:

  NAME
       回声 - 显示一行文字
[...]
       -e使反斜杠逃逸间pretation

POSIX 7条规定这种行为 rel=\"nofollow\">:


  

...]与命令的标准输出,在替代的端部去除的一个或多个字符序列


Working with printf in a bash script, adding no spaces after "\n" does not create a newline, whereas adding a space creates a newline, e. g.:

  1. No space after "\n"

    NewLine=`printf "\n"`
    echo -e "Firstline${NewLine}Lastline"
    

    Result:

    FirstlineLastline
    

  2. Space after "\n "

    NewLine=`printf "\n "`
    echo -e "Firstline${NewLine}Lastline"
    

    Result:

    Firstline
     Lastline
    

Question: Why doesn't 1. create the following result:

Firstline 
Lastline

I know that this specific issue could have been worked around using other techniques, but I want to focus on why 1. does not work.

Edited: When using echo instead of printf, I get the expected result, but why does printf work differently?

    NewLine=`echo "\n"`
    echo -e "Firstline${NewLine}Lastline"

Result:

    Firstline
    Lastline

解决方案

The backtick operator removes trailing new lines. See 3.4.5. Command substitution at http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html

Note on edited question

Compare:

[alvaro@localhost ~]$ printf "\n"

[alvaro@localhost ~]$ echo "\n"
\n
[alvaro@localhost ~]$ echo -e "\n"


[alvaro@localhost ~]$

The echo command doesn't treat \n as a newline unless you tell him to do so:

NAME
       echo - display a line of text
[...]
       -e     enable interpretation of backslash escapes

POSIX 7 specifies this behaviour here:

[...] with the standard output of the command, removing sequences of one or more characters at the end of the substitution

这篇关于例如printf的在bash不会创建一个新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆