Code Monkey home page Code Monkey logo

pawk's Introduction

PAWK - A Python line processor (like AWK)

PAWK aims to bring the full power of Python to AWK-like line-processing.

Here are some quick examples to show some of the advantages of pawk over AWK.

The first example transforms /etc/hosts into a JSON map of host to IP:

cat /etc/hosts | pawk -B 'd={}' -E 'json.dumps(d)' '!/^#/ d[f[1]] = f[0]'

Breaking this down:

  1. -B 'd={}' is a begin statement initializing a dictionary, executed once before processing begins.
  2. -E 'json.dumps(d)' is an end statement expression, producing the JSON representation of the dictionary d.
  3. !/^#/ tells pawk to match any line not beginning with #.
  4. d[f[1]] = f[0] adds a dictionary entry where the key is the second field in the line (the first hostname) and the value is the first field (the IP address).

And another example showing how to bzip2-compress + base64-encode a file:

cat pawk.py | pawk -E 'base64.encodestring(bz2.compress(t))'

AWK example translations

Most basic AWK constructs are available. You can find more idiomatic examples below in the example section, but here are a bunch of awk commands and their equivalent pawk commands to get started with:

Print lines matching a pattern:

ls -l / | awk '/etc/'
ls -l / | pawk '/etc/'

Print lines not matching a pattern:

ls -l / | awk '!/etc/'
ls -l / | pawk '!/etc/'

Field slicing and dicing (here pawk wins because of Python's array slicing):

ls -l / | awk '/etc/ {print $5, $6, $7, $8, $9}'
ls -l / | pawk '/etc/ f[4:]'

Begin and end end actions (in this case, summing the sizes of all files):

ls -l | awk 'BEGIN {c = 0} {c += $5} END {print c}'
ls -l | pawk -B 'c = 0' -E 'c' 'c += int(f[4])'

Print files where a field matches a numeric expression (in this case where files are > 1024 bytes):

ls -l | awk '$5 > 1024'
ls -l | pawk 'int(f[4]) > 1024'

Matching a single field (any filename with "t" in it):

ls -l | awk '$NF ~/t/'
ls -l | pawk '"t" in f[-1]'

Installation

It should be as simple as:

pip install pawk

But if that doesn't work, just download the pawk.py, make it executable, and place it somewhere in your path.

Expression evaluation

PAWK evaluates a Python expression or statement against each line in stdin. The following variables are available in local context:

  • line - Current line text, including newline.
  • l - Current line text, excluding newline.
  • n - The current 1-based line number.
  • f - Fields of the line (split by the field separator -F).
  • nf - Number of fields in this line.
  • m - Tuple of match regular expression capture groups, if any.

In the context of the -E block:

  • t - The entire input text up to the current cursor position.

If the flag -H, --header is provided, each field in the first row of the input will be treated as field variable names in subsequent rows. The header is not output. For example, given the input:

count name
12 bob
34 fred

We could do:

$ pawk -H '"%s is %s" % (name, count)' < input.txt
bob is 12
fred is 34

To output a header as well, use -B:

$ pawk -H -B '"name is count"' '"%s is %s" % (name, count)' < input.txt
name is count
bob is 12
fred is 34

Module references will be automatically imported if possible. Additionally, the --import <module>[,<module>,...] flag can be used to import symbols from a set of modules into the evaluation context.

eg. --import os.path will import all symbols from os.path, such as os.path.isfile(), into the context.

Output

Line actions

The type of the evaluated expression determines how output is displayed:

  • tuple or list: the elements are converted to strings and joined with the output delimiter (-O).
  • None or False: nothing is output for that line.
  • True: the original line is output.
  • Any other value is converted to a string.

Start/end blocks

The rules are the same as for line actions with one difference. Because there is no "line" that corresponds to them, an expression returning True is ignored.

$ echo -ne 'foo\nbar' | pawk -E t
foo
bar

Command-line usage

Usage: cat input | pawk [<options>] <expr>

A Python line-processor (like awk).

See https://github.com/alecthomas/pawk for details. Based on
http://code.activestate.com/recipes/437932/.

Options:
  -h, --help            show this help message and exit
  -I <filename>, --in_place=<filename>
                        modify given input file in-place
  -i <modules>, --import=<modules>
                        comma-separated list of modules to "from x import *"
                        from
  -F <delim>            input delimiter
  -O <delim>            output delimiter
  -L <delim>            output line separator
  -B <statement>, --begin=<statement>
                        begin statement
  -E <statement>, --end=<statement>
                        end statement
  -s, --statement       DEPRECATED. retained for backward compatibility
  -H, --header          use first row as field variable names in subsequent
                        rows
  --strict              abort on exceptions

Examples

Line processing

Print the name and size of every file from stdin:

find . -type f | pawk 'f[0], os.stat(f[0]).st_size'

Note: this example also shows how pawk automatically imports referenced modules, in this case os.

Print the sum size of all files from stdin:

find . -type f | \
	pawk \
		--begin 'c=0' \
		--end c \
		'c += os.stat(f[0]).st_size'

Short-flag version:

find . -type f | pawk -B c=0 -E c 'c += os.stat(f[0]).st_size'

Whole-file processing

If you do not provide a line expression, but do provide an end statement, pawk will accumulate each line, and the entire file's text will be available in the end statement as t. This is useful for operations on entire files, like the following example of converting a file from markdown to HTML:

cat README.md | \
	pawk --end 'markdown.markdown(t)'

Short-flag version:

cat README.md | pawk -E 'markdown.markdown(t)'

pawk's People

Contributors

alecthomas avatar chirayuk avatar em1181 avatar jas32096 avatar jonathanbp avatar svisser avatar tos-kamiya avatar vegemash avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pawk's Issues

Multiple regex matches

Feature request to enable things like:

cat /etc/hosts | pawk '!/^#/ and !/^127'

This would require a whole new way of parsing. It should parse it as a python expression with some syntactic sugar for regex matches.

Create tag 0.8.1

The PyPI release is at v0.8.1. Looking at issue #22 and the head commit, I don't think there were any changes to the actual pawk.py script. However, I am trying to add pawk to Homebrew PR, and it would be helpful if the two sources were in sync.

in place editing

This seems really cool...any chance for supporting in-place editing of files? I understand that awk doesn't support in-place editing but am used to the perl -i option and find it super-handy.

Add a option to keep the header row

The newly added feature -H is great! However, it is even better if a user is allowed to process the header row as well. For example, in your example of

count name
12 bob
34 fred

pawk -H '"%s is %s" % (name, count)' < input.txt produces the following results.

name is count
bob is 12
fred is 34

Or at least, there should be an option allowing users to do so. One simple use case is to use pawk to extract columns from a text file. Users often want to keep the header row in this situation.

Statement in line action not working

When I try to use a statement in the line action of pawk I get a syntax error. To reproduce just run a line taken direct from the README of pawk

pawk -B c=0 -E c 'c += os.stat(f[0]).st_size'

This results in this error:

File "/usr/local/lib/python2.7/site-packages/pawk.py", line 41, in _compile
self._codeobj = compile(self.cmd, 'EXPR', 'exec' if statement else 'eval')
File "EXPR", line 1
c += os.stat(f[0]).st_size
^
SyntaxError: invalid syntax

Any statement using "=" in the line action fails similarly. Statements seem to work in -B and -E actions, but only expressions work for line actions.

This is under python 2.7.5. Pawk does not report a version.

Broken on python 3.8

Pawk crashes with, as far as I can tell, any pattern and expression if running on python 3.8.

~/pawk >>> echo '1 1' | python3.7 pawk 'f[0]'                                                ±[●][master]
1
~/pawk >>> echo '1 1' | python3.8 pawk 'f[0]'                                                ±[●][master]
Traceback (most recent call last):
  File "pawk", line 5, in <module>
    main()
  File "/home/archer/pawk/pawk.py", line 246, in main
    run(sys.argv, sys.stdin, sys.stdout)
  File "/home/archer/pawk/pawk.py", line 233, in run
    actions = [Action.from_options(options, arg) for arg in args]
  File "/home/archer/pawk/pawk.py", line 233, in <listcomp>
    actions = [Action.from_options(options, arg) for arg in args]
  File "/home/archer/pawk/pawk.py", line 88, in from_options
    return cls(pattern=pattern, cmd=cmd, have_end_statement=(options.end is not None), negate=negate, strict=options.strict)
  File "/home/archer/pawk/pawk.py", line 83, in __init__
    self._compile(have_end_statement)
  File "/home/archer/pawk/pawk.py", line 96, in _compile
    self._codeobj = compile_command(self.cmd)
  File "/home/archer/pawk/pawk.py", line 65, in compile_command
    return compile(tree, 'EXPR', 'exec')
ValueError: Name node can't be used with 'None' constant

Invoke pawk from a python script?

Is it possible to invoke pawk from a python script, without using subprocess.run?

I am imagining something like:

import pawk

my_pawk_program = ' .... '

results = pawk.run(my_pawk_program)

build error: 'pypandoc' has no attribute 'convert'

Hello, I'm building pawk on an Arch Linux machine with packages:
pawk v.0.7.0
pypandoc 1.8.1
The build process halts on the following error:

Traceback (most recent call last):                                                                  
  File "/home/gaetan/.cache/pikaur/build/python-pawk/src/pawk-0.7.0/setup.py", line 16, in <module> 
    long_description = pypandoc.convert('README.md', 'rst')                                         
AttributeError: module 'pypandoc' has no attribute 'convert'                                        

I have also tried pip install pawk (pawk version is 0.6.5) and building git zip file with the same result.

Verification: the pypandoc I use has convert_file and convert_text methods, but no convert

>>> dir(pypandoc)
['DEFAULT_TARGET_FOLDER', 'Iterable', 'Union', '__all__', '__author__', '__author_email__', '__builtins__', '__cached__', '__classifiers__', '__description__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__pandoc_path', '__path__', '__python_requires__', '__setup_requires__', '__spec__', '__url__', '__version', '__version__', '_as_unicode', '_check_log_handler', '_classify_pandoc_logging', '_convert_input', '_ensure_pandoc_path', '_get_base_format', '_get_pandoc_version', '_identify_format_from_path', '_identify_input_type', '_identify_path', '_is_network_path', '_validate_formats', 'absolute_import', 'cast_bytes', 'cast_unicode', 'clean_pandocpath_cache', 'clean_version_cache', 'convert_file', 'convert_text', 'download_pandoc', 'ensure_pandoc_installed', 'ensure_pandoc_maximal_version', 'ensure_pandoc_minimal_version', 'get_pandoc_formats', 'get_pandoc_formats_pre_1_18', 'get_pandoc_path', 'get_pandoc_version', 'glob', 'handler', 'logger', 'logging', 'normalize_format', 'os', 'pandoc_download', 'print_function', 'py3compat', 're', 'string_types', 'subprocess', 'sys', 'tempfile', 'textwrap', 'url2path', 'urlparse', 'with_statement']
>>> 

I tried to use convert_file in place of convert but could not make setup.py run without error.

0 vs 1-based index

n - The current 1-based line number.

This seems a little bit confusing as the field index is 0-based. I suggest make them consistent. It is probably better to use 0-base index as that's what Python does.

[new feature] add action(s) before the output evaluation on each line

Hi,

Can you please add a feature to evaluate action(s) on each line before the output evaluation. For example, if I want to exchange two columns, I have to list the order in full, in the current implementation.

printf '%s ' {1..5} | pawk 'f[0],f[2],f[1],f[3],f[4]'
1 3 2 4 5

something like this:

printf '%s ' {1..5} | pawk -a 'f[2],f[1] = f[1],f[2]' 'f'

This is very convenient if we have too many columns. Or we just want to have a minor modification on each line and output results.

Thanks much!

I broke pawk 0.8.0 😱

I only tested Poetry build with my patch to pyproject.toml but made no further tests.

I added no scripts entries, thus no pawk script is installed 😕. Moreover, the bin directory containing python and hermit binaries is unnecessary.

I'll have a look and submit another PR...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.