Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you explain this sed one-liner?

Tags:

linux

unix

sed

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

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

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

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

in this command?

like image 468
Alby Avatar asked Dec 22 '22 00:12

Alby


1 Answers

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

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.

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

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

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

like image 172
Tomas Avatar answered Dec 24 '22 02:12

Tomas