Linux的tac命令的多种实现

本文最后更新于2015年6月8日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!

搜索关键字:
  • use awk to read a file in reverse
参考链接:
参考解答:
$ awk '{a[++n]=$0}END{for(i=n;i>0;--i)print a[i]}' /path/to/input
$ awk '{a[n++]=$0}END{while(n--)print a[n]}' /path/to/input
$ sed '1!G;h;$!d' /path/to/input
$ sed -n '1!G;h;$p' /path/to/input
$ cat /path/to/input | perl -e 'print reverse <>'
# cat /path/to/input | python -c "import sys
> for line in reversed(sys.stdin.readlines()): print line.rstrip()"

注意,上面这个Python版本的无法写在一行上面,否则会报错:

$ cat /path/to/input | python -c "import sys;for line in reversed(sys.stdin.readlines()): print line.rstrip()"
  File "<string>", line 1
    import sys;for line in reversed(sys.stdin.readlines()): print line.rstrip()
                 ^
SyntaxError: invalid syntax

$ cat /path/to/input | python -c "import sys\nfor line in reversed(sys.stdin.readlines()): print line.rstrip()"
  File "<string>", line 1
    import sys\nfor line in reversed(sys.stdin.readlines()): print line.rstrip()
                                                                               ^
SyntaxError: unexpected character after line continuation character
搜索关键字:
  • python one line for loop error
解释:

根据Python的语法规则,while和for语句前面是不能有分号的(复合语句都不能全写在一行):

while, for can’t have semicolon before, they need to be on one line. If you looked at Python grammar:

compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | decorated
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

you will see that the statements that are part of compound_stmt need to be one one line alone. The only statements that can be separated by semicolon are simple_stmt group:

simple_stmt ::=  expression_stmt
                 | assert_stmt
                 | assignment_stmt
                 | augmented_assignment_stmt
                 | pass_stmt
                 | del_stmt
                 | print_stmt
                 | return_stmt
                 | yield_stmt
                 | raise_stmt
                 | break_stmt
                 | continue_stmt
                 | import_stmt
                 | global_stmt
                 | exec_stmt

=EOF=

声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!
https://ixyzero.com/blog/archives/2215.html

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注