到目前为止,我已经能够找到如何在文件的开头添加一行,但这不是我想要的.我将在一个例子中展示它
文件内容
some text at the beginning
Run Code Online (Sandbox Code Playgroud)
结果
<added text> some text at the beginning
Run Code Online (Sandbox Code Playgroud)
它是类似的,但我不想用它创建任何新的线...
sed如果可能的话,我想这样做.
kev*_*kev 284
sed 可以在一个地址上运作:
$ sed -i '1s/^/<added text> /' file
Run Code Online (Sandbox Code Playgroud)
1s你在这里的每个答案都看到了什么神奇的东西?线路寻址!.
想要添加<added text>前10行吗?
$ sed -i '1,10s/^/<added text> /' file
Run Code Online (Sandbox Code Playgroud)
或者您可以使用Command Grouping:
$ { echo -n '<added text> '; cat file; } >file.new
$ mv file{.new,}
Run Code Online (Sandbox Code Playgroud)
小智 31
如果要在文件的开头添加一行,则需要\n在上面的最佳解决方案中添加字符串的末尾.
最好的解决方案是添加字符串,但是对于字符串,它不会在文件末尾添加一行.
sed -i '1s/^/your text\n/' file
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 26
如果文件只有一行,您可以使用:
sed 's/^/insert this /' oldfile > newfile
Run Code Online (Sandbox Code Playgroud)
如果它不止一行.之一:
sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile
Run Code Online (Sandbox Code Playgroud)
我已经包含后者,以便你知道如何做行范围.这两个都用您要插入的文本"替换"受影响的行上的起始行标记.你也可以(假设你sed的足够现代)使用:
sed -i 'whatever command you choose' filename
Run Code Online (Sandbox Code Playgroud)
进行就地编辑.
Nic*_*Roz 17
使用子外壳:
echo "$(echo -n 'hello'; cat filename)" > filename
Run Code Online (Sandbox Code Playgroud)
不幸的是,命令替换将删除文件末尾的换行符。为了保留它们,可以使用:
echo -n "hello" | cat - filename > /tmp/filename.tmp
mv /tmp/filename.tmp filename
Run Code Online (Sandbox Code Playgroud)
既不需要分组也不需要命令替换。
小智 10
您可以使用 cat -
printf '%s' "some text at the beginning" | cat - filename
Run Code Online (Sandbox Code Playgroud)
小智 10
要仅插入换行符:
sed '1i\\'
Run Code Online (Sandbox Code Playgroud)
小智 9
Hi with carriage return:
sed -i '1s/^/your text\n/' file
Run Code Online (Sandbox Code Playgroud)
我的两分钱:
sed -i '1i /path/of/file.sh' filename
Run Code Online (Sandbox Code Playgroud)
即使是包含正斜杠的字符串,这也将起作用 "/"
小智 5
请注意,在OS X上sed -i <pattern> file,失败.但是,如果您提供备份扩展sed -i old <pattern> file,则会file在file.old创建时进行适当修改.然后file.old,您可以在脚本中删除.
小智 5
有一个非常简单的方法:
echo "your header" > headerFile.txt
cat yourFile >> headerFile.txt
Run Code Online (Sandbox Code Playgroud)