【问题标题】:Open and write data to text file using Bash?使用 Bash 打开并将数据写入文本文件?
【发布时间】:2022-03-15 21:14:53
【问题描述】:

如何在 Linux 中通过 shell 脚本自动将数据写入文本文件?

我能够打开文件。但是,我不知道如何向它写入数据。

【问题讨论】:

标签: bash shell


【解决方案1】:

简短的回答:

echo "some data for the file" >> fileName

但是,echo doesn't deal with end of line characters (EOFs) in an ideal way。所以,如果你要追加多于一行,请使用printf:

printf "some data for the file\nAnd a new line" >> fileName

>> 和 > 运算符对于重定向命令的输出非常有用,它们可以与多个其他 bash 命令一起使用。

【讨论】:

  • 这个操作员叫什么名字?我想找一本关于它的手册。
  • 运算符 > 将输出重定向到一个文件,如果该文件存在,则覆盖该文件。 >> 将附加到现有文件。
  • 谢谢,这是维基页面的链接,以防有人需要en.wikipedia.org/wiki/…
  • 如果您需要以root权限执行此操作,请这样做:sudo sh -c 'echo "some data for the file" >> fileName'
  • 如果我的文字类似于this 并且出于任何原因我不能使用curl 或wget 怎么办?
【解决方案2】:
#!/bin/sh

FILE="/path/to/file"

/bin/cat <<EOM >$FILE
text1
text2 # This comment will be inside of the file.
The keyword EOM can be any text, but it must start the line and be alone.
 EOM # This will be also inside of the file, see the space in front of EOM.
EOM # No comments and spaces around here, or it will not work.
text4 
EOM

【讨论】:

  • 不错的多行输出。
  • 新手将受益于确切知道如何处理此文件。如何保存,如何运行等
  • 请解释一下,而不是简单地贴一段代码。这会让它对每个人都更有帮助——尤其是新手。
  • 在这种情况下,带有 $some_var 等变量的脚本会丢失。怎么解决?
【解决方案3】:

您可以将命令的输出重定向到文件:

$ cat file > copy_file

或附加到它

$ cat file >> copy_file

如果你想直接写命令是echo 'text'

$ echo 'Hello World' > file

【讨论】:

  • 如果你需要root权限:sudo sh -c 'cat file &gt; /etc/init/gunicorn.conf'(感谢lukaserat上面的评论)
【解决方案4】:
#!/bin/bash

cat > FILE.txt <<EOF

info code info 
info code info
info code info

EOF 

【讨论】:

  • 对您的代码的解释将大大有助于使其对其他人更有用。甚至像“here document”和“redirection”这样的词汇标注也可以将搜索者指向其他资源。
  • 这样的事情不需要解释。
  • 当您已经知道答案时,永远不需要解释。对我来说,由于缺乏细节,上面的代码没有帮助。
  • EOF 之后 - 应该没有空格。
【解决方案5】:

我知道这是一个该死的老问题,但是由于 OP 是关于脚本的,而且由于 google 将我带到这里,因此还应该提到同时打开文件描述符以进行读取和写入。

#!/bin/bash

# Open file descriptor (fd) 3 for read/write on a text file.
exec 3<> poem.txt

    # Let's print some text to fd 3
    echo "Roses are red" >&3
    echo "Violets are blue" >&3
    echo "Poems are cute" >&3
    echo "And so are you" >&3

# Close fd 3
exec 3>&-

然后cat终端上的文件

$ cat poem.txt
Roses are red
Violets are blue
Poems are cute
And so are you

这个例子导致文件poem.txt 被打开以在文件描述符3 上读写。它还表明*nix 盒子知道更多的fd,然后只是stdin、stdout 和stderr (fd 0,1,2)。它实际上有很多。通常内核可以分配的最大文件描述符数可以在/proc/sys/file-max 或/proc/sys/fs/file-max 中找到,但是使用任何大于 9 的 fd 都是危险的,因为它可能与 shell 内部使用的 fd 冲突。所以不要打扰,只使用 fd 的 0-9。如果您在 bash 脚本中需要更多 9 个文件描述符,则无论如何都应该使用不同的语言 :)

总之,fd 可以有很多有趣的用途。

【讨论】:

    【解决方案6】:

    我喜欢这个答案:

    cat > FILE.txt <<EOF
    
    info code info 
    ...
    EOF
    

    但如果您只想在文件末尾添加一些内容而不删除已经存在的内容,建议您使用cat &gt;&gt; FILE.txt &lt;&lt; EOF

    像这样:

    cat >> FILE.txt <<EOF
    
    info code info 
    ...
    EOF
    

    【讨论】:

    • 添加一些解释,说明此答案如何帮助 OP 解决当前问题
    【解决方案7】:

    根据@lycono 的要求,将我的评论作为答案移动

    如果您需要以 root 权限执行此操作,请按以下方式操作:

    sudo sh -c 'echo "some data for the file" >> fileName'
    

    【讨论】:

    • 您可能希望避免仅仅为了打印字符串而运行 root shell。尝试 echo "some data for the file" | sudo tee -a fileName &gt;/dev/null 仅以 root 身份运行 tee。
    【解决方案8】:

    对于此处文档不可用的环境(Makefile、Dockerfile 等),您通常可以使用printf 以获得合理易读且有效的解决方案。

    printf '%s\n' '#!/bin/sh' '# Second line' \
        '# Third line' \
        '# Conveniently mix single and double quotes, too' \
        "# Generated $(date)" \
        '# ^ the date command executes when the file is generated' \
        'for file in *; do' \
        '    echo "Found $file"' \
        'done' >outputfile
    

    【讨论】:

    • 您在上面的评论 尝试 echo "some data for the file" | sudo tee -a fileName >/dev/null 仅以 root 身份运行 tee。 非常有用!
    【解决方案9】:

    我认为有一些非常好的答案,但没有简明扼要地总结所有可能性;因此:

    这里大多数答案背后的核心原则是redirection。两个是写入文件的重要重定向运算符:

    重定向输出:

    echo 'text to completely overwrite contents of myfile' > myfile
    

    附加重定向输出

    echo 'text to add to end of myfile' >> myfile
    

    这里的文档

    提到的其他人,除了来自echo 'text' 之类的固定输入源,您还可以通过“Here Document”以交互方式写入文件,上面的 bash 手册链接中也有详细说明。那些答案,例如

    cat > FILE.txt <<EOF` or `cat >> FILE.txt <<EOF
    

    使用相同的重定向运算符,但通过“Here Documents”添加另一层。在上述语法中,您通过cat 的输出写入FILE.txt。只有在给交互式输入提供了一些特定字符串(在本例中为“EOF”)之后才会进行写入,但这可以是任何字符串,例如:

    cat > FILE.txt <<'StopEverything'` or `cat >> FILE.txt <<'StopEverything'
    

    也可以。此处 Documents 还会查找各种分隔符和其他有趣的解析字符,因此请查看文档以获取更多信息。

    这里的字符串

    有点复杂,更多的是理解重定向和 Here Documents 语法的练习,但您可以将 Here Document 样式语法与标准重定向运算符组合成 Here String:

    重定向 cat 输入的输出

    cat > myfile <<<'text to completely overwrite contents of myfile'
    

    附加 cat 输入的重定向输出

    cat >> myfile <<<'text to completely overwrite contents of myfile'
    

    【讨论】:

      【解决方案10】:

      这种方法有效并且是最好的

      cat > (filename) <<EOF
      Text1...
      Text2...
      EOF
      

      基本上文本将搜索关键字“EOF”,直到它终止写入/附加文件

      【讨论】:

        【解决方案11】:

        如果你使用变量,你可以使用

        first_var="Hello"
        second_var="How are you"
        

        如果你想连接两个字符串并将其写入文件,那么在下面使用

        echo "${first_var} - ${second_var}" > ./file_name.txt
        

        您的file_name.txt 内容将是“Hello - How are you”

        【讨论】:

        • 请分享您的答案的更多细节,以便其他人可以从中学习
        • 非常有用。验证和工作!谢谢。
        【解决方案12】:

        这里也可以使用document和vi,下面的脚本会生成一个3行和变量插值的FILE.txt

        VAR=Test
        vi FILE.txt <<EOFXX
        i
        #This is my var in text file
        var = $VAR
        #Thats end of text file
        ^[
        ZZ
        EOFXX
        

        然后文件将有如下 3 行。 "i" 是启动 vi 插入模式,类似地用 Esc 和 ZZ 关闭文件。

        #This is my var in text file
        var = Test
        #Thats end of text file
        

        【讨论】:

        • 请注意,其他答案中提到的使用“cat”而不是“vi”的相同方法会减少额外的输入。
        猜你喜欢
        • 2012-11-24
        • 1970-01-01
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多