diff --git a/README.md b/README.md index be99b49..d01ff19 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ python3 -m build ``` 5) Upload the distribution packages with twine. For the username, use `__token__`. For the password, use a -[test.pypi.org API token](https://test.pypi.org/manage/account/#api-tokens): + [test.pypi.org API token](https://test.pypi.org/manage/account/#api-tokens): ```shell python3 -m twine upload --repository testpypi dist/* diff --git a/setup.cfg b/setup.cfg index 4a935ba..47506f5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -3,7 +3,7 @@ [metadata] name = py-regex-replace -version = 0.0.1 +version = 0.0.2 author = Daniel Langbein author_email = daniel@systemli.org description = perform regex-replacement on stdin and output result to stdout @@ -33,3 +33,4 @@ where = src ; https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html console_scripts= py-regex-replace = py_regex_replace.main:main + py-replace = py_replace.main:main diff --git a/src/py_replace/__init__.py b/src/py_replace/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/py_replace/main.py b/src/py_replace/main.py new file mode 100755 index 0000000..c557441 --- /dev/null +++ b/src/py_replace/main.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import argparse +import sys + + +def main(): + text, repl, string, count = parse_args() + + occurrences = string.count(text) + if occurrences != count: + print(f'[ERROR] Expected {count} occurrences of text in string, but got {occurrences}.') + exit(1) + + string = string.replace(text, repl) + + print(string, end='') + + +def parse_args(): + parser = argparse.ArgumentParser(prog='py-regex-replace') + + parser.add_argument('--text', '-t', + help='text to replace', + required=True, type=str) + parser.add_argument('--repl', '-r', + help='replacement', + required=True, type=str) + parser.add_argument('--count', '-c', + help='expected count of text in string', + default=1, type=int) + + args = parser.parse_args() + + string = sys.stdin.read() + if len(string) == 0: + print('[WARNING] The given string is empty.', file=sys.stderr) + + return args.text, args.repl, string, args.count + + +if __name__ == '__main__': + main() diff --git a/test/test1.sh b/test/test.sh similarity index 100% rename from test/test1.sh rename to test/test.sh diff --git a/test/test_multiline_pattern.sh b/test/test_multiline_pattern.sh new file mode 100644 index 0000000..ae25503 --- /dev/null +++ b/test/test_multiline_pattern.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env sh + +string='alpha = a +beta = b +Exec = foo bar baz +end = EOF' +pattern='= b\nExec =' +repl='=' + +string="$(printf '%s' "${string}" | ../src/py_regex_replace/main.py -p "${pattern}" -r "${repl}" -c 1)" + +printf 'RESULT>>>\n%s\n<<>>\n%s\n<<