搜索关键字:
- use awk to read a file in reverse
参考链接:
- http://www.tek-tips.com/viewthread.cfm?qid=965087
- http://stackoverflow.com/questions/742466/how-can-i-reverse-the-order-of-lines-in-a-file
- http://unix.stackexchange.com/questions/9356/how-can-i-print-lines-from-file-backwards-without-using-tac
- http://stackoverflow.com/questions/14258616/using-tac-to-read-a-file-in-reverse
- http://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python
- =
- http://www.bashoneliners.com/oneliners/oneliner/popular/
- https://github.com/janosgyerik/bashoneliners
参考解答:
$ 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
解释:
- http://stackoverflow.com/questions/2043453/executing-python-multi-line-statements-in-the-one-line-command-line
- http://stackoverflow.com/questions/18602119/python-command-line-argument-semicolon-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=