【问题标题】:Bash: add string to the end of the file without line breakBash:将字符串添加到文件末尾而不换行
【发布时间】:2012-02-03 02:18:06
【问题描述】:

如何在不换行的情况下将字符串添加到文件末尾?

例如,如果我使用 >> 它将添加到文件末尾并带有换行符:

cat list.txt
yourText1
root@host-37:/# echo yourText2 >> list.txt
root@host-37:/# cat list.txt
yourText1
yourText2

我想在 yourText1 之后添加 yourText2

root@host-37:/# cat list.txt
yourText1yourText2

【问题讨论】:

  • echo -n 似乎是您要查找的命令。

标签: linux bash awk echo cat


【解决方案1】:

以上答案对我不起作用。发布一个 Python 实现,以防万一有人觉得它有用。

python -c "txtfile = '/my/file.txt' ; f = open(txtfile, 'r') ; d = f.read().strip() ; f.close() ; d = d + 'the data to append' ; open(txtfile, 'w').write(d)"

【讨论】:

    【解决方案2】:

    只需改用printf,因为它不会默认打印新行:

    printf "final line" >> file
    

    测试

    让我们创建一个文件,然后添加一个没有尾随新行的额外行。注意我使用cat -vet 来查看新行。

    $ seq 2 > file
    $ cat -vet file
    1$
    2$
    $ printf "the end" >> file
    $ cat -vet file
    1$
    2$
    the end
    

    【讨论】:

    • 由于一个非常模糊的原因,echo -n 在从 Ansible shell 运行时不起作用。你的回答让我很开心。
    【解决方案3】:
    sed '$s/$/yourText2/' list.txt > _list.txt_ && mv -- _list.txt_ list.txt
    

    如果你的 sed 实现支持 -i 选项,你可以使用:

    sed -i.bck '$s/$/yourText2/' list.txt
    

    使用第二种解决方案,您也将拥有一个备份(第一种,您需要手动进行)。

    或者:

    ex -sc 's/$/yourText2/|w|q' list.txt 
    

    perl -i.bck -pe's/$/yourText2/ if eof' list.txt
    

    【讨论】:

    • 感谢 ex/vim 版本这么简单!
    • 注意:如果您的文本文件来自 Mac/Dos,这将无法识别 EoL 字符。您需要先在文件上运行 dos2unix。
    【解决方案4】:

    可以使用echo的-n参数。像这样:

    $ touch a.txt
    $ echo -n "A" >> a.txt
    $ echo -n "B" >> a.txt
    $ echo -n "C" >> a.txt
    $ cat a.txt
    ABC
    

    编辑:啊哈,您已经有一个包含字符串和换行符的文件。好吧,无论如何我都会把它留在这里,也许我们对某人有用。

    【讨论】:

    • 非常正确,先生,我会这样做。另外,如果您不是从文件开始,那么>> 将使用您提供的任何扩展名或根本不使用它,例如我最喜欢的代码行:$ cat ~/.ssh/id_rsa.pub | ssh itsme@nopasswordcheckneeded.com 'cat >> ~/.ssh/authorized_keys' 然后下一行是$ ssh-add -K 和walla!每次我需要远程访问那台机器时,不再提示密码
    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2012-08-03
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多