将sed d和sed a脚本合并成一个单独的脚本。

huangapple go评论61阅读模式
英文:

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&#39;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 &#39;1d; 2a abc&#39; 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'

注意:命令 ac 直接写入输出而不是模式空间的原因很可能是会破坏使用行号进行地址范围的方式。

英文:

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 &#39;1a\
abc&#39; -e &#39;1d&#39;
[GNU]$ sed -e &#39;1a abc&#39; -e &#39;1d&#39;

However, the easiest is just to use the replace command c:

[POSIX]$ sed -e &#39;1c\
abc&#39;
[GNU]$ sed -e &#39;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.

huangapple
  • 本文由 发表于 2023年2月16日 11:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定