使用 Bash 打开并将数据写入文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11162406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open and write data to text file using Bash?
提问by Adnan
How can I write data to a text file automatically by shell scripting in Linux?
如何通过 Linux 中的 shell 脚本自动将数据写入文本文件?
I was able to open the file. However, I don't know how to write data to it.
我能够打开文件。但是,我不知道如何向其写入数据。
回答by Triton Man
echo "some data for the file" >> fileName
回答by coolfire
#!/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
回答by ssedano
You can redirect the output of a command to a file:
您可以将命令的输出重定向到文件:
$ cat file > copy_file
or append to it
或附加到它
$ cat file >> copy_file
If you want to write directly the command is echo 'text'
如果你想直接写命令是 echo 'text'
$ echo 'Hello World' > file
回答by baetacos
#!/bin/bash
cat > FILE.txt <<EOF
info code info
info code info
info code info
EOF
回答by tobi
I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.
我知道这是一个该死的老问题,但是由于 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>&-
Then cat
the file on terminal
然后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 :)
这个例子导致文件poe.txt 被打开以在文件描述符3 上读写。它还表明*nix 框比stdin、stdout 和stderr (fd 0,1,2) 知道更多的fd。它实际上拥有很多。通常,内核可以分配的最大文件描述符数可以在/proc/sys/file-max
或/proc/sys/fs/file-max
但使用任何大于 9 的 fd 是危险的,因为它可能与 shell 内部使用的 fd 冲突。所以不要打扰,只使用 fd 的 0-9。如果您在 bash 脚本中需要更多的 9 个文件描述符,您无论如何都应该使用不同的语言:)
Anyhow, fd's can be used in a lot of interesting ways.
无论如何,fd 可以以很多有趣的方式使用。
回答by Marat
I like this answer:
我喜欢这个答案:
cat > FILE.txt <<EOF
info code info
...
EOF
but would suggest cat >> FILE.txt << EOF
if you want just add something to the end of the file without wiping out what is already exists
但会建议cat >> FILE.txt << EOF
您是否只想在文件末尾添加一些内容而不清除已经存在的内容
Like this:
像这样:
cat >> FILE.txt <<EOF
info code info
...
EOF
回答by lukaserat
Moving my comment as an answer, as requested by @lycono
按照@lycono 的要求,将我的评论作为答案
If you need to do this with root privileges, do it this way:
如果您需要使用 root 权限执行此操作,请按以下方式执行:
sudo sh -c 'echo "some data for the file" >> fileName'
回答by tripleee
For environments where here documents are unavailable (Makefile
, Dockerfile
, etc) you can often use printf
for a reasonably legible and efficient solution.
对于此处文档不可用(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
回答by topher217
I thought there were a few perfectly fine answers, but no concise summary of all possibilities; thus:
我认为有一些完美的答案,但没有对所有可能性的简明总结;因此:
The core principal behind most answers here is redirection. Two are important redirection operators for writing to files:
这里大多数答案背后的核心原则是重定向。两个是用于写入文件的重要重定向运算符:
Redirecting Output:
重定向输出:
echo 'text to completely overwrite contents of myfile' > myfile
echo 'text to completely overwrite contents of myfile' > myfile
Appending Redirected Output
附加重定向输出
echo 'text to add to end of myfile' >> myfile
echo 'text to add to end of myfile' >> myfile
Here Documents
这里的文件
Others mentioned, rather than from a fixed input source like echo 'text'
, you could also interactively write to files via a "Here Document", which are also detailed in the link to the bash manual above. Those answers, e.g.
其他人提到,echo 'text'
您还可以通过“此处文档”以交互方式写入文件,而不是来自固定输入源,如上面的 bash 手册链接。那些答案,例如
cat > FILE.txt <<EOF
or cat >> FILE.txt <<EOF
cat > FILE.txt <<EOF
或者 cat >> FILE.txt <<EOF
make use of the same redirection operators, but add another layer via "Here Documents". In the above syntax, you write to the FILE.txt via the output of cat
. The writing only takes place after the interactive input is given some specific string, in this case 'EOF', but this could be any string, e.g.:
使用相同的重定向运算符,但通过“此处文档”添加另一层。在上述语法中,您通过 .txt 的输出写入 FILE.txt cat
。写入仅在交互式输入被赋予一些特定字符串后发生,在本例中为“EOF”,但这可以是任何字符串,例如:
cat > FILE.txt <<'StopEverything'
or cat >> FILE.txt <<'StopEverything'
cat > FILE.txt <<'StopEverything'
或者 cat >> FILE.txt <<'StopEverything'
would work just as well. Here Documents also look for various delimiters and other interesting parsing characters, so have a look at the docs for further info on that.
也能正常工作。此处文档还查找各种分隔符和其他有趣的解析字符,因此请查看文档以获取更多信息。
Here Strings
这里字符串
A bit convoluted, and more of an exercise in understanding both redirection and Here Documents syntax, but you could combine Here Document style syntax with standard redirect operators to become a Here String:
有点复杂,更多的是理解重定向和 Here Documents 语法的练习,但您可以将 Here Document 样式语法与标准重定向运算符结合起来,成为一个 Here 字符串:
重定向 cat 输入的输出cat > myfile <<<'text to completely overwrite contents of myfile'
cat > myfile <<<'text to completely overwrite contents of myfile'
cat >> myfile <<<'text to completely overwrite contents of myfile'
cat >> myfile <<<'text to completely overwrite contents of myfile'
回答by onoffon
this is my answer. $ cat file > copy_file
这是我的答案。$ cat 文件> copy_file