到目前为止,我已经能够找出如何在文件的开头添加一行,但这并不完全是我想要的。我将用一个例子来说明:

文件内容

some text at the beginning

结果

<added text> some text at the beginning

它很相似,但是我不想用它创建任何新的行…

如果可能的话,我希望用sed来做这件事。


当前回答

注意,在OS X上,sed -i <pattern>文件失败。但是,如果您提供了一个备份扩展名sed -i old <pattern> file,那么file将在file的位置被修改。旧的是创造出来的。然后您可以删除文件。老在你的剧本里。

其他回答

使用echo方法,如果你像我一样使用macOS/BSD,就不要像其他人建议的那样使用-n开关。我喜欢为文本定义一个变量。

所以它是这样的:

Header="my complex header that may have difficult chars \"like these quotes\" and line breaks \n\n "

{ echo "$Header"; cat "old.txt"; } > "new.txt"
mv new.txt old.txt

别名是另一种解决方案。添加到你的init rc/ env文件:

addtail () { find . -type f ! -path "./.git/*" -exec sh -c "echo $@ >> {}" \; }
addhead () { find . -type f ! -path "./.git/*" -exec sh -c  "sed -i '1s/^/$@\n/' {}" \; }

用法:

addtail "string to add at the beginning of file"
addtail "string to add at the end of file"

我找到的最简单的解决方法是:

echo -n "<text to add>" | cat - myFile.txt | tee myFile.txt

注:

Remove | tee myFile.txt if you don't want to change the file contents. Remove the -n parameter if you want to append a full line. Add &> /dev/null to the end if you don't want to see the output (the generated file). This can be used to append a shebang to the file. Example: # make it executable (use u+x to allow only current user) chmod +x cropImage.ts # append the shebang echo '#''!'/usr/bin/env ts-node | cat - cropImage.ts | tee cropImage.ts &> /dev/null # execute it ./cropImage.ts myImage.png

在文件顶部添加一行:

sed -i '1iText to add\'

只是为了好玩,这里有一个使用ed的解决方案,它没有不能处理空文件的问题。您可以把它放到一个shell脚本中,就像这个问题的任何其他答案一样。

ed Test <<EOF
a

.
0i
<added text>
.
1,+1 j
$ g/^$/d
wq
EOF

上面的脚本将要插入的文本添加到第一行,然后连接第一行和第二行。为了避免ed在无效连接错误时退出,它首先在文件末尾创建一个空行,如果它仍然存在,则稍后删除它。

限制:如果<added text>恰好等于单个句点,此脚本将不起作用。