以下一个班轮反过来打印出文件的内容
$ sed -n '1!G;h;$p' test.txt
Run Code Online (Sandbox Code Playgroud)
当sed逐行读取文件时怎么可能?你能解释一下这个意思吗?
n 旗1!Gh$p 在这个命令?
这将完成相同的工作tac,即恢复行的顺序.将sed脚本重写为伪代码,意味着:
$line_number = 1;
foreach ($input in $input_lines) {
// current input line is in $input
if ($line_number != 1) // 1!
$input = $input + '\n' + $hold; // G
$hold = $input; // h
$line_number++
}
print $input; // $p
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,sed语言非常具有表现力:-) 1!和$所谓的地址,它们在运行命令时设置条件.1!意思是不在第一行,$意思是在最后.Sed有一个辅助存储寄存器被调用hold space.
有关更多信息,请info sed在linux控制台上输入(这是最好的文档).
-n禁用print $input循环本身的默认命令.
术语pattern space和hold space变量的等价物$input以及$hold本例中的(分别).
n flag -> Disable auto-printing.
1! -> Any line except the first one.
G -> Append a newline and content of 'hold space' to 'pattern space'
h -> Replace content of 'hold space' with content of 'pattern space'
$ -> Last line.
p -> print
Run Code Online (Sandbox Code Playgroud)
因此,它意味着:正如我所理解的那样:反转文件的内容.
编辑添加一些解释(感谢potong,看他对原版的评论):
地址,类似于1并$绑定到下一个命令,分组使用{...}或单独使用它们.因此,在这种情况下,1!适用于G并$到p,而h没有连接到一个地址,并适用于所有的地址.那是$!G和$!{G}都是一样的.