Created
July 21, 2016 13:55
-
-
Save benjamingorman/39561e9eea693d0922836a48b6b5b8ab to your computer and use it in GitHub Desktop.
Command line string splitting tool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Splits every line in STDIN using str.split. Prints | |
each field on STDOUT using the indices given as arguments | |
to the script. | |
Usage: | |
echo 'foo bar baz' | pysplit 2 1 0 | |
echo 'foo,bar,baz' | pysplit , 2 1 0 | |
""" | |
import sys | |
def is_int(string): | |
try: | |
int(string) | |
return True | |
except ValueError: | |
return False | |
chars = None | |
if is_int(sys.argv[1]): | |
indices = map(int, sys.argv[1:]) | |
else: # Use the given chars for splitting | |
chars = sys.argv[1] | |
indices = map(int, sys.argv[2:]) | |
for line in sys.stdin: | |
line = line.strip() | |
if chars: | |
line_parts = line.split(chars) | |
else: | |
line_parts = line.split() | |
for n, index in enumerate(indices): | |
sys.stdout.write(line_parts[index]) | |
if n == len(indices) - 1: | |
sys.stdout.write('\n') | |
else: | |
sys.stdout.write(' ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment