我有一个输入文件
Werkzeug==2.0.2 # https://github.com/pallets/werkzeug
ipdb==0.13.9 # https://github.com/gotcha/ipdb
psycopg2==2.9.1 # https://github.com/psycopg/psycopg2
watchgod==0.7 # https://github.com/samuelcolvin/watchgod
# Testing
# ------------------------------------------------------------------------------
mypy==0.910 # https://github.com/python/mypy
django-stubs==1.8.0 # https://github.com/typeddjango/django-stubs
pytest==6.2.5 # https://github.com/pytest-dev/pytest
pytest-sugar==0.9.4 # https://github.com/Frozenball/pytest-sugar
djangorestframework-stubs==1.4.0 # https://github.com/typeddjango/djangorestframework-stubs
# Documentation
# ------------------------------------------------------------------------------
sphinx==4.2.0 # https://github.com/sphinx-doc/sphinx
sphinx-autobuild==2021.3.14 # https://github.com/GaretJax/sphinx-autobuild
# Code quality
# ------------------------------------------------------------------------------
flake8==3.9.2 # https://github.com/PyCQA/flake8
flake8-isort==4.0.0 # https://github.com/gforcada/flake8-isort
coverage==6.0.2 # https://github.com/nedbat/coveragepy
black==21.9b0 # https://github.com/psf/black
pylint-django==2.4.4 # https://github.com/PyCQA/pylint-django
pylint-celery==0.3 # https://github.com/PyCQA/pylint-celery
pre-commit==2.15.0 # https://github.com/pre-commit/pre-commit
# Django
# ------------------------------------------------------------------------------
factory-boy==3.2.0 # https://github.com/FactoryBoy/factory_boy
django-debug-toolbar==3.2.2 # https://github.com/jazzband/django-debug-toolbar
django-extensions==3.1.3 # https://github.com/django-extensions/django-extensions
django-coverage-plugin==2.0.1 # https://github.com/nedbat/django_coverage_plugin
pytest-django==4.4.0 # https://github.com/pytest-dev/pytest-django我正在尝试使用以下命令在#之前提取以pytest开头的每一行的部分
sed -nE "s/(^pytest.+)#/\1/p" ./requirements/local.txt
预期产出
pytest==6.2.5
pytest-sugar==0.9.4
pytest-django==4.4.0 实际输出
pytest==6.2.5 https://github.com/pytest-dev/pytest
pytest-sugar==0.9.4 https://github.com/Frozenball/pytest-sugar
pytest-django==4.4.0 https://github.com/pytest-dev/pytest-django有什么能帮上忙的吗?
这些裁判并没有帮助解决这个特殊的问题。
发布于 2022-01-14 10:20:16
您错过了#之后的正则表达式。这应该能解决这个问题:
$ sed -nE "s/(^pytest.+)#.*/\1/p" ./requirements/local.txt发布于 2022-01-14 10:20:14
使用sed
sed -nE 's/^(pytest[^=]*=[^[:blank:]]*).*/\1/p' file
pytest==6.2.5
pytest-sugar==0.9.4
pytest-django==4.4.0然而,grep -o解决方案甚至更简单:
grep -o '^pytest[^=]*=[^[:blank:]]*' file
pytest==6.2.5
pytest-sugar==0.9.4
pytest-django==4.4.0解释:
^pytest:匹配start[^=]*:匹配0或更多的字符( ==:除外)匹配0或更多的非空格字符。
发布于 2022-01-14 10:24:21
第一种解决方案:和awk,您可以尝试如下。在这里使用match awk函数,在GNU awk中编写和测试,应该可以在任何情况下工作。简单的解释是,使用match函数的awk匹配正则^pytest[^ ]*,匹配pytest的起始值,直到第一次出现空格,然后用awk的substr函数打印匹配值。
awk 'match($0,/^pytest[^ ]*/){print substr($0,RSTART,RLENGTH)}' Input_file第二个解决方案:使用GNU awk,然后尝试使用它的RS变量。
awk -v RS='(^|\n)pytest[^ ]*' 'RT{sub(/^\n*/,"",RT);print RT}' Input_filehttps://stackoverflow.com/questions/70709008
复制相似问题