如何理解sed脚本编程中的美元符号($)? [英] how to understand dollar sign ($) in sed script programming?

查看:53
本文介绍了如何理解sed脚本编程中的美元符号($)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家.我不明白 sed 脚本编程中的美元符号 ($),它代表文件的最后一行还是 sed 的计数器?我想颠倒/etc/passwd 的行顺序(模拟tac").如下:

everybody. I don't understand dollar sign ($) in sed script programming, it is stand for last line of a file or a counter of sed? I want to reverse order of lines (emulates "tac") of /etc/passwd. like following:

$ cat /etc/passwd | wc -l  ----> 52        // line numbers

$  sed '1!G;h;$!d' /etc/passwd | wc -l ----> 52 // working correctly

$ sed '1!G;h;$d' /etc/passwd | wc -l ----> 1326    // no ! followed by $

$ sed '1!G;h;$p' /etc/passwd | wc -l ----> 1430    // instead !d by p

最后两个例子不正确,谁能告诉我美元符号代表什么意思?

Last two example don't work right, who can tell me what mean does dollar sign stand for?

推荐答案

所有命令都正常工作".他们只是做一些你意想不到的事情.让我们考虑第一个版本:

All the commands "work right." They just do something you don't expect. Let's consider the first version:

sed '1!G;h;$!d

从前两个命令开始:

1!G; h

执行这两个命令后,模式空间和保持空间都包含到目前为止读取的所有行,但顺序相反.

After these two commands have been executed, the pattern space and the hold space both contain all the lines reads so far but in reverse order.

此时,如果我们什么都不做,sed 将执行其默认操作,即打印模式空间.所以:

At this point, if we do nothing, sed would take its default action which is to print the pattern space. So:

  • 读取第一行后,将打印第一行.

  • After the first line is read, it would print the first line.

读取第二行后,将打印第二行,然后打印第一行.

After the second line is read, it would print the second line followed by the first line.

读取第三行后,将打印第三行,然后是第二行,然后是第一行.

After the third line is read, it would print the third line, followed by the second line, followed by the first line.

等等.

如果我们正在模拟 tac,我们不希望那样.我们希望它只有在读完最后一行后才打印.所以,这就是以下命令的用武之地:

If we are emulating tac, we don't want that. We want it to print only after it has read in the last line. So, that is where the following command comes in:

$!d

$ 表示最后一行.$! 表示非最后一行.$!d 表示如果我们不在最后一行则删除.因此,这告诉 sed 删除模式空间,除非我们在最后一行,在这种情况下,它将被打印,以相反的顺序显示所有行.

$ means the last line. $! means not-the-last-line. $!d means delete if we are not on the last line. Thus, this tells sed to delete the pattern space unless we are on the last line, in which case it will be printed, displaying all lines in reverse order.

考虑到这一点,请考虑您的第二个示例:

With that in mind, consider your second example:

sed '1!G;h;$d'

这将打印除最后一个之外的所有部分 tac.

This prints all the partial tacs except the last one.

你的第三个例子:

sed '1!G;h;$p'

这将打印所有部分 tac 直到最后一个,但最后一个打印两次:$p 是最后一个模式空间的显式打印除了无论如何都会发生的隐式打印之外的行.

This prints all the partial tacs up through the last one but the last one is printed twice: $p is an explicit print of the pattern space for the last line in addition to the implicit print that would happen anyway.

这篇关于如何理解sed脚本编程中的美元符号($)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆