如何从unix或solaris中的文件中删除包含字符串的行
我的文件如下,
test1
test2
test3
test4
test5
我想删除包含 test2 的行,因此我使用了如下命令,但不是仅删除“test2”行,而是删除了整个文件,并且 fize-size 变为零。
bash# cat /aaa/bbb/ccc/myfile | sed -e '/test2/ d' > /aaa/bbb/ccc/myfile
bash# ls -l total 0
-rw-r--r-- 1 root root 0 3月 11 17:41 myfile
有人能建议一下,命令有什么问题吗?
I have myfile as follows
test1
test2
test3
test4
test5
I want to delete line containing test2, so I used command as follows, but instead of removing only 'test2' line its removed whole file and fize-size became zero.
bash# cat /aaa/bbb/ccc/myfile | sed -e '/test2/ d' > /aaa/bbb/ccc/myfile
bash# ls -l total 0
-rw-r--r-- 1 root root 0 3月 11 17:41 myfile
can anybody suggest , whats wrong in command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
除非您有 GNU sed(带有“-i”选项),并且您使用的是 Solaris,所以您可能没有,否则您别无选择,只能写入临时文件:
更新:使用
ed
unless you have GNU sed (with the "-i" option), and you're on Solaris so you probably don't, you have no choice but to write to temp file:
update: edit the file in-place with
ed
我不知道 perl 是否是 Solaris 上的标准。如果是这种情况,您可以使用:
I don't know if perl is standard on Solaris. If this is the case, you can use:
不幸的是,输出重定向立即清空输出文件。因此,您必须使用不同的文件作为输出文件,例如:
或者您可以执行类似的操作:
但由于缓冲,这不是很可靠。如果输出程序 (
tee
) 在 sed 完成读取之前写入文件,这将导致数据损坏。也许您还可以尝试使用程序
buffer
或mbuffer
作为tee
的替代品,您可以在其中指定缓冲区大小。但我在快速试验中并没有取得可靠的成功。Unfortunately the output redirection immediately empties the output file. Therefore you have to use a different file as output file, eg:
Or you could do e.g. something like that:
But due to buffering this is not very reliable. If the output program (
tee
) writes to the file before sed has finished reading, this will lead to corrupt data.Maybe you could also experiment with the programs
buffer
ormbuffer
as substitute fortee
there you can specify buffer sizes. But I didn't have reliable success on a fast trial.尝试
Try
您可以简单地使用旧版:
You can simply use the good old ed:
您还可以使用
grep
:请注意,与
sed
一样,您不应该覆盖正在读取的文件,因此您可以像这样调用它:You can also use
grep
:Be aware that as with
sed
, you shouldn't overwrite the file you are reading from, so you can invoke it like this:Solaris,假设您使用的不是过时的版本,应该至少已经带有 bash 3。所以只使用 bash
Solaris, assuming you are not on an archaic version, should already come with at least bash 3. So using just bash
下面的代码对我来说工作得很好......
the following code is workign fine for me...
您可以在 AWK 中将整个文件读入数组:
由于重定向不是由 shell 完成的,因此不会执行早期截断。
You can read the whole file into an array in AWK:
Since redirection is not done by the shell, early truncation is not performed.
所以使用:
So use: