如何在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"

其他回答

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

如果使用变量,可以使用

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

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

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

你的file_name.txt内容将是"Hello - How are you"

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

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

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

简单的回答是:

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