awkg是一个类似awk的文本处理工具,由python语言提供支持
awkg的Python项目详细描述
awkg
awkg
是使用现代python语言的类似于awk
的实用程序。
awk
非常简单、快速而且非常方便。但是,它的领域特定约束
有时会妨碍我们。awkg
遵循awk
设计的步骤(包括它对名称的约定)
展示了现代Python的全部力量。
Python的一大堆现成的现有图书馆当然可以被导入和使用。
安装
# Install from pypy $ pip install awkg # Install from github $ pip install git+https://github.com/thammegowda/awkg.git
cli用法:
$ awkg -h
usage: awkg [-h] [-i INP] [-o OUT] [-F FS] [-OFS OFS] [-ORS ORS]
[-b BEGIN_SCRIPT] [-e END_SCRIPT] [-im IMPORTS] [-it INIT_PATH]
[-v]
inline_script
awkg is an awk-like text-processing tool powered by python language
positional arguments:
inline_script Inline python script
optional arguments:
-h, --help show this help message and exit
-i INP, --inp INP Input file path; None=STDIN
-o OUT, --out OUT Output file path; None=STDOUT
-F FS, -FS FS, --field-sep FS
the input field separator. Default=None implies white
space
-OFS OFS, --out-field-sep OFS
the out field separator. Default=None implies same as
input FS.
-ORS ORS, --out-rec-sep ORS
the output record separator. Default=None implies same
as input RS.
-b BEGIN_SCRIPT, --begin BEGIN_SCRIPT
BEGIN block. initialize variables or whatever
-e END_SCRIPT, --end END_SCRIPT
END block. Print summaries or whatever
-im IMPORTS, --import IMPORTS
Imports block. Specify a list of module names to be
imported.Semicolon (;) is the delimiter. Ex:
json;numpy as np
-it INIT_PATH, --init INIT_PATH
The rc file that initializes environment.Default is
$HOME/.awkg.py
-v, --version show program's version number and exit
示例
计算每个序列中单词的平均值和标准差
cat data/train.src | awkg -b 'arr=[]; import numpy as np''arr.append(NF)'\ -e 'arr=np.array(arr); print(f"{NR} lines from {FNAME}, mean={arr.mean():.2f}; std={arr.std():.4f}")'
过滤记录
# use print() explicitely
cat data/train.src | awkg 'if NF >= 25: print(*R)'
Assign boolean expression to special variable RET to trigger implicit print
cat data/train.src | awkg 'RET = NF >= 25'
# print respects the OFS value
cat data/train.src | awkg 'if NF >= 25: print(NR, NF)' -OFS='\t'
特殊变量
NF
:字段数NR
:记录号R
:具有当前记录的所有列的数组。R0
:类似于$0
,它在拆分成R
之前存储输入行,因为python是 不允许$
在标识符中,它被重命名为R0
RET
:当此变量设置为true
隐式print(*R)
的真值时,将触发FS
:输入字段分隔符OFS
:输出字段分隔符;除非显式设置,OFS=FS
ORS
:输出记录分隔符RS
(当前未使用)_locals
,_globals
-本地和全局范围内的所有变量
除了上述变量之外,您还可以使用任何有效的python标识符
默认导入模块
默认情况下,这些模块是导入的
sys
os
re
from pathlib import Path