如何在Linux中通过shell脚本自动将数据写入文本文件?
我打开了文件。但是,我不知道如何写入数据。
如何在Linux中通过shell脚本自动将数据写入文本文件?
我打开了文件。但是,我不知道如何写入数据。
当前回答
也可以使用这里的文档和vi,下面的脚本生成一个FILE.txt 3行和变量插值
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
其他回答
对于这里的文档不可用的环境(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
你可以将命令的输出重定向到一个文件:
$ cat file > copy_file
或者附加到它
$ cat file >> copy_file
如果你想直接写入命令是echo 'text'
$ echo 'Hello World' > file
我喜欢这个答案:
cat > FILE.txt <<EOF
info code info
...
EOF
但建议cat >> file .txt << EOF,如果你只是想在文件末尾添加一些东西,而不清除已经存在的东西
是这样的:
cat >> FILE.txt <<EOF
info code info
...
EOF
简单的回答是:
echo "some data for the file" >> fileName
但是,echo不能以理想的方式处理行尾字符。所以,如果你要追加多行,用printf:
printf "some data for the file\nAnd a new line" >> fileName
>>和>操作符对于重定向命令输出非常有用,它们与其他多个bash命令一起使用。
#!/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