bash sed 不替换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14553804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:22:27  来源:igfitidea点击:

sed not replacing lines

bashreplacesed

提问by Jason Kennaly

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.

我有一个包含 1 行文本的文件,名为output. 我对文件有写访问权限。我可以从编辑器中毫无问题地更改它。

$ cat output
1
$ ls -l o*
-rw-rw-r-- 1 jbk jbk 2 Jan 27 18:44 output

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:

我想要做的是用新值(1 或 0)替换此文件中的第一行(也是唯一行)。在我看来,sed 应该非常适合:

$ sed '1 c\ 0' output
 0
$ cat output
1

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.

但它永远不会改变文件。我试过它在反斜杠处分布在 2 行上,并带有双引号,但我无法让它在第一行中放置 0(或其他任何东西)。

回答by jahroy

Sed operates on streams and prints its output to standard out.

Sed 对流进行操作并将其输出打印到标准输出。

It does not modify the input file.

它不会修改输入文件。

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

The above command invokes sedon input-fileand redirectsthe output to a new file named output-file.

上述命令调用sedinput-file重定向输出到一个名为的新文件output-file

Depending on your platform, you might be able to use sed's -ioption to modify files in place:

根据您的平台,您也许可以使用 sed 的-i选项来修改文件:

sed -i.bak 's/foo/bar/g' input-file

NOTE:

笔记:

Not all versions of sed support -i.

并非所有版本的 sed 都支持-i

Also, different versions of sed implement -idifferently.

此外,不同版本的 sed 实现方式-i不同。

On some platforms you MUSTspecify a backup extension (on others you don't have to).

在某些平台上,您必须指定备份扩展(在其他平台上,您不必指定)。

回答by Kevin

Since this is an incredibly simple file, sed may actually be overkill. It sounds like you want the file to have exactly one character: a '0' or a '1'.

由于这是一个非常简单的文件,因此 sed 实际上可能有点矫枉过正。听起来您希望文件只有一个字符:“0”或“1”。

It may make better sense in this case to just overwrite the file rather than to edit it, e.g.:

在这种情况下,只覆盖文件而不是编辑文件可能更有意义,例如:

echo "1" > output 

or

或者

echo "0" > output