您能解释一下这种sed单线吗? [英] Can you explain this sed one-liner?

查看:85
本文介绍了您能解释一下这种sed单线吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的衬纸反面打印出文件内容

The following one liner prints out the content of the file in reverse

$ sed -n '1!G;h;$p' test.txt

当sed逐行读取文件时,怎么办?你能解释一下

How is it possible when sed reads the file line by line? Can you explain the meaning of

  • n标志
  • 1!
  • G
  • h
  • $p
  • n flag
  • 1!
  • G
  • h
  • and $p

在此命令中

推荐答案

这将与tac做同样的工作,即恢复行的顺序. 将sed脚本重写为伪代码,这意味着:

This will do the same job as tac, i.e. revert the order of rows. Rewriting the sed script to pseudocode, it means:

$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

如您所见,sed语言非常有表现力:-) 1!$称为地址,它们在应运行命令时提供条件. 1!表示不在第一行,$表示在末尾. sed有一个辅助存储寄存器,称为hold space.

As you can see, the sed language is very expressive :-) the 1! and $ are so called addresses, which put conditions when the command should be run. 1! means not on the first row, $ means at the end. Sed has one auxiliary memory register which is called hold space.

有关更多信息,请在Linux控制台上键入info sed(这是最佳文档).

For more information type info sed on linux console (this is the best documentation).

-n在循环本身中禁用默认的print $input命令.

-n disables the default print $input command in the loop itself.

在此示例中,术语pattern spacehold space分别等效于变量$input$hold.

The terms pattern space and hold space are equivalents of the variables $input and $hold (respectively) in this example.

这篇关于您能解释一下这种sed单线吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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