到目前为止,我已经能够找出如何在文件的开头添加一行,但这并不完全是我想要的。我将用一个例子来说明:
文件内容
some text at the beginning
结果
<added text> some text at the beginning
它很相似,但是我不想用它创建任何新的行…
如果可能的话,我希望用sed来做这件事。
到目前为止,我已经能够找出如何在文件的开头添加一行,但这并不完全是我想要的。我将用一个例子来说明:
文件内容
some text at the beginning
结果
<added text> some text at the beginning
它很相似,但是我不想用它创建任何新的行…
如果可能的话,我希望用sed来做这件事。
当前回答
插入换行符:
sed '1i\\'
其他回答
插入换行符:
sed '1i\\'
如果文件只有一行,你可以使用:
sed 's/^/insert this /' oldfile > newfile
如果它不止一行。之一:
sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile
我已经包括了后者,以便您知道如何进行行范围。这两种方法都用要插入的文本“替换”受影响行的开始行标记。您还可以(假设您的sed足够现代)使用:
sed -i 'whatever command you choose' filename
进行就地编辑。
echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt
第一个tac反向传输文件(最后一行先传输),因此“要插入的文本”出现在最后。第2个tac再次将其换行,因此插入的行位于开头,原始文件保持原始顺序。
你可以用cat -
printf '%s' "some text at the beginning" | cat - filename
我找到的最简单的解决方法是:
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