首页 文章

如何将输出附加到文本文件的末尾

提问于
浏览
293

如何将命令的输出附加到文本文件的末尾?

8 回答

  • 7

    将输出定向到文件时,请使用 >> 而不是 >

    your_command >> file_to_append_to
    

    如果 file_to_append_to 不存在,则会创建它 .

    Example:

    $ echo "hello" > file
    $ echo "world" >> file
    $ cat file 
    hello
    world
    
  • 19

    您可以使用>>运算符 . 这会将命令中的数据附加到文本文件的末尾 .

    要测试此尝试运行:

    echo "Hi this is a test" >> textfile.txt
    

    这样做几次然后运行:

    cat textfile.txt
    

    您将看到您的文本已多次附加到textfile.txt文件中 .

  • 441

    append 文件使用 >>

    echo“hello world”>> read.txt
    cat read.txt
    echo“hello siva”>> read.txt
    cat read.txt
    然后输出应该是hello world
    你好,湿婆

    overwrite 文件使用 >

    echo“hello tom”> read.txt
    cat read.txt
    那么输出就是你好汤姆

  • 7

    使用 command >> file_to_append_to 附加到文件 .

    例如 echo "Hello" >> testFile.txt

    CAUTION: 如果您只使用一个 > ,您将完全覆盖该文件的内容 . 为确保不会发生这种情况,您可以将 set -o noclobber 添加到 .bashrc .

    这可确保如果您不小心将 command > file_to_append_to 键入现有文件,它将提醒您该文件已存在 . 示例错误消息: file exists: testFile.txt

    因此,当您使用 > 时,它只允许您创建新文件,而不是覆盖现有文件 .

  • 26

    使用 >> 运算符将文本附加到文件 .

  • 13

    对于整个问题:

    cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
    

    这会将720行(30 * 24)附加到o.txt中,然后根据当前日期重命名文件 .

    每小时用cron运行上面的,或者

    while :
    do
        cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
        sleep 3600
    done
    
  • 30

    我建议你做两件事:

    • 在shell脚本中使用 >> 将内容追加到特定文件 . 文件名可以修复或使用某种模式 .

    • 设置每小时cronjob以触发shell脚本

  • 63

    例如,您的文件包含:

    1.  mangesh@001:~$ cat output.txt
        1
        2
        EOF
    

    如果你想在文件末尾附加,那么---->记住'text'>>'filename'之间的空格

    2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt 
        1
        2
        EOF
        somthing to append
    

    并覆盖文件的内容:

    3.  mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx
        somthing new to write
    

相关问题