如何在Linux中通过shell脚本自动将数据写入文本文件?
我打开了文件。但是,我不知道如何写入数据。
如何在Linux中通过shell脚本自动将数据写入文本文件?
我打开了文件。但是,我不知道如何写入数据。
当前回答
如果使用变量,可以使用
first_var="Hello"
second_var="How are you"
如果你想连接两个字符串并将其写入文件,那么使用下面的方法
echo "${first_var} - ${second_var}" > ./file_name.txt
你的file_name.txt内容将是"Hello - How are you"
其他回答
简单的回答是:
echo "some data for the file" >> fileName
但是,echo不能以理想的方式处理行尾字符。所以,如果你要追加多行,用printf:
printf "some data for the file\nAnd a new line" >> fileName
>>和>操作符对于重定向命令输出非常有用,它们与其他多个bash命令一起使用。
你可以将命令的输出重定向到一个文件:
$ cat file > copy_file
或者附加到它
$ cat file >> copy_file
如果你想直接写入命令是echo 'text'
$ echo 'Hello World' > file
我想有几个非常好的答案,但没有对所有可能性的简明总结;因此:
大多数答案背后的核心原则是重定向。有两个重要的重定向操作符用于写入文件:
重定向输出:
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'
也可以使用这里的文档和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
#!/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