【问题标题】:Paste Command Not Recognizing Linebreak (/n) In Script粘贴命令无法识别脚本中的换行符 (/n)
【发布时间】:2017-01-05 22:59:30
【问题描述】:

我正在使用以下代码将标题“Both”和一个空行添加到文件中。

sed -i '1i Both \n' file1

当我打开文件时,我可以看到换行符。

但是,当我使用以下命令粘贴文件时,它会删除 shell 中的换行符。

paste file1 file2 | column -s $'\t' -t | sed '1i\\'

有人知道为什么粘贴无法识别吗?

更具体地说,/n 字符正在被识别,但如果换行符在同一行中,paste 将消除它。

正在输出什么:

Header1     Header2
abc         def
ghi         jkl

应该是什么:

Header1     Header2

abc         def
ghi         jkl

我知道它会删除换行符,因为当我只在一个文件中添加新行时,它看起来像这样:

Header1     Header2               
            def
abc         jkl
ghi

作为临时解决方法,我使用sed -i '1i Both \n----' file1 强制粘贴打印新行,因为它不为空:

Header1     Header2
----        ----        
abc         def
ghi         jkl

而且,它保留了换行符,所以我想,当将两个文件粘贴在一起时,如何将新行保留在一行中?

【问题讨论】:

  • 你能发布你得到的和你期望的吗?
  • 刚刚提供了更多细节。
  • 与此同时,我正在使用sed -i '1i Both \n----' 强制识别新行,因为它不为空,并在标题和数据之间提供了一个分隔符。
  • 嗯? “被paste 识别”?您正在对paste输出 执行此操作。 paste 看不到它的输出做了什么;它无法与 sed 进程交互。

标签: linux shell unix sed command


【解决方案1】:

这里不需要sed。观察:

# defining functions here to make this a standalone reproducer
# remove these and change <(file1) to just file1 to use files instead
file1() { printf '%s\n' Header1 abc ghi; }
file2() { printf '%s\n' Header2 def jkl; }

# use braces to create a code block, and redirect that whole block to your output file
{
  printf '%s\n' Both ''                        # header, then blank line
  paste <(file1) <(file2) | column -s $'\t' -t # body content
} >out.txt                                     # redirection

...显然,如果您根本不将输出重定向到文件,则不需要重定向,也不需要块。这也更有效率:不需要column 的输出被sed 读取然后写入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-20
    • 2012-01-27
    • 2017-11-19
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多