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

我打开了文件。但是,我不知道如何写入数据。


当前回答

这种方法是有效的,也是最好的

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

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

其他回答

对于这里的文档不可用的环境(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

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

#!/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

This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max or /proc/sys/fs/file-max but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)

无论如何,fd可以以许多有趣的方式使用。

移动我的评论作为一个答案,由@lycono要求

如果你需要用root权限来做这件事,这样做:

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

我喜欢这个答案:

cat > FILE.txt <<EOF

info code info 
...
EOF

但建议cat >> file .txt << EOF,如果你只是想在文件末尾添加一些东西,而不清除已经存在的东西

是这样的:

cat >> FILE.txt <<EOF

info code info 
...
EOF

我想有几个非常好的答案,但没有对所有可能性的简明总结;因此:

大多数答案背后的核心原则是重定向。有两个重要的重定向操作符用于写入文件:

重定向输出:

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'

效果也一样。在这里,文档还查找各种分隔符和其他有趣的解析字符,因此请查看文档以获得有关这方面的进一步信息。

这里的字符串

这有点复杂,更多的是在理解重定向和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'