使用 sed 向文件添加新行

Adding new line to file with sed

我想用 sed 在数据文件的顶部添加一个新行,并向该行写入一些内容。

我按照 How to add a blank line before the first line in a text file with awk 中的建议进行了尝试:

sed '1i\ \' ./filename.txt

但它在文件第一行的开头打印了一个反斜杠,而不是创建一个新行。如果我尝试将它们全部放在同一行(“1i\”:i 命令末尾 \ 之后的额外字符),终端也会抛出错误。

输入:

1 2 3 4 
1 2 3 4 
1 2 3 4 

预期输出

14
1 2 3 4 
1 2 3 4 
1 2 3 4 

基本上您是在连接两个文件。包含一行和原始文件的文件。顾名思义,这是 cat:

的任务
cat - file <<< 'new line'
# or 
echo 'new line' | cat - file

- 代表 stdin.

如果您的 shell 支持,您还可以将 cat 与命令替换一起使用:

cat <(echo 'new line') file

顺便说一句,sed 应该是:

sed '1i\new line' file
$ sed '1i' file
14
1 2 3 4
1 2 3 4
1 2 3 4

但为了清晰、简单、可扩展性、健壮性、可移植性和软件的所有其他理想属性,仅使用 awk:

$ awk 'NR==1{print "14"} {print}' file
14
1 2 3 4
1 2 3 4
1 2 3 4