英文:
combine sed d and sed a scripts to a single script
问题
我想合并
```sed -i '1d' xz.txt```
```sed -i '1a abc' xz.txt```
我尝试了
```sed -i -e '1d' -e '1a abc' xz.txt```
期望得到
```456
abc
789
但我得到了
789
sed(GNU sed)4.7
但它不起作用,有帮助吗?
<details>
<summary>英文:</summary>
file xz.txt
123
456
789
I want to merge
sed -i '1d' xz.txt
sed -i '1a abc' xz.txt
I tried
sed -i -e '1d' -e '1a abc' xz.txt
expect to get
456
abc
789
but I got
456
789
sed (GNU sed) 4.7
but it doesn't work, any help?
</details>
# 答案1
**得分**: 3
```plaintext
Sed 逐行处理,第一个命令 `1d` - 删除了第一行,第一行消失了,再也没有了第一行,这就是为什么第二个命令 `1a abc` 没有起作用的原因。以下是正确的写法:
$ sed '1d; 2a abc' f
456
abc
789
英文:
Sed goes line by line, first command 1d
- deleted 1st line, 1st line is gone, there is no more 1st line, that is why second command 1a abc
didn't work. Here is how it should be:
$ sed '1d; 2a abc' f
456
abc
789
答案2
得分: 1
发生的情况是删除语句会自动结束处理序列:
[1addr]a\
text
将文本写入标准输出,如前所述(是的,这里有一个换行符)[2addr]d
:删除模式空间 并 开始下一个周期- 来源:Posix)
由于 a
命令不修改模式空间,只是将内容写入 stdout
,你可以简单地执行:
[POSIX]$ sed -e '1a\
abc' -e '1d'
[GNU]$ sed -e '1a abc' -e '1d'
然而,最简单的方法是使用替换命令 c
:
[POSIX]$ sed -e '1c\
abc'
[GNU]$ sed -e '1c abc'
注意:命令 a
和 c
直接写入输出而不是模式空间的原因很可能是会破坏使用行号进行地址范围的方式。
英文:
What is going on is that the delete statement automatically ends the processing sequence:
> * [1addr]a\
<br />
> text
Write text to standard output as described previously (yes there is a new-line here)
> * [2addr]d
: Delete the pattern space and start the next cycle
> <sub>Source: Posix)</sub>
As the a
command does not modify the pattern space but just writes to stdout
, you can simply do
[POSIX]$ sed -e '1a\
abc' -e '1d'
[GNU]$ sed -e '1a abc' -e '1d'
However, the easiest is just to use the replace command c
:
[POSIX]$ sed -e '1c\
abc'
[GNU]$ sed -e '1c abc`
Note: The reason the commands a
and c
write directly to the output and not to the pattern space is most likely that it would mess up the address ranging using line-numbers.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论