问题描述
我有一个包含1行文本的文件,称为output
.我对该文件具有写权限.我可以毫无问题地从编辑器进行更改.
I have a file with 1 line of text, called output
. I have write access to the file. I can change it from an editor with no problems.
$ cat output
1
$ ls -l o*
-rw-rw-r-- 1 jbk jbk 2 Jan 27 18:44 output
我想要做的是用新值1或0替换此文件中的第一行(也是唯一行).在我看来sed应该是完美的选择:
What I want to do is replace the first (and only) line in this file with a new value, either a 1 or a 0. It seems to me that sed should be perfect for this:
$ sed '1 c\ 0' output
0
$ cat output
1
但是它永远不会更改文件.我已经尝试过将它放在反斜杠的2行中,并用双引号引起来,但是我无法让它在第一行中添加0(或其他任何值).
But it never changes the file. I've tried it spread over 2 lines at the backslash, and with double quotes, but I cannot get it to put a 0 (or anything else) in the first line.
推荐答案
Sed在流上运行并将其输出打印到标准输出.
Sed operates on streams and prints its output to standard out.
它不会修改输入文件.
当您希望将其输出捕获到文件中时,通常会这样使用:
It's typically used like this when you want to capture its output in a file:
#
# replace every occurrence of foo with bar in input-file
#
sed 's/foo/bar/g' input-file > output-file
上面的命令在input-file
上调用sed
并将重定向输出到名为output-file
的新文件.
The above command invokes sed
on input-file
and redirects the output to a new file named output-file
.
取决于您的平台,您也许可以使用sed的-i
选项在适当位置修改文件:
Depending on your platform, you might be able to use sed's -i
option to modify files in place:
sed -i.bak 's/foo/bar/g' input-file
注意:
并非所有版本的sed都支持-i
.
Not all versions of sed support -i
.
此外,不同版本的sed实现-i
的方式也不同.
Also, different versions of sed implement -i
differently.
在某些平台上,您必须指定备份扩展名(在其他平台上则不需要).
On some platforms you MUST specify a backup extension (on others you don't have to).
这篇关于sed不替换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!