How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?

烈酒焚心 提交于 2019-12-06 13:32:11

问题


Apparently the answer to my question "Can I restrict nose coverage output to directory (rather than package)?" is no, but I can pass a --coverage-package=PACKAGE option to nose with the package name of each .py file in the directory.

So for example, if the directory contains:

foo.py
bar.py
baz.py

...then I would need to use the command:

nosetests --with-coverage --coverage-package=foo --coverage-package=bar --coverage-package=baz

So my question is, can someone write some shell script code (preferably sh or bash) to take all the filenames in the current directory with a .py extension and generate the above command-line (with the .py extensions removed)? My bash skills are quite limited. (I'm tempted to just do it in Python.)


回答1:


nosetests --with-coverage $(for f in *.py; do echo --cover-package="${f%.*}"; done)

The trick is here is using parameter substitution to remove the file extension.

${f%.*}



回答2:


And if you care to do it correct (which means, don't allow wordsplitting to cut your filenames apart or unexpected globbing to expand to random filenames), use an array:

files=(*.py)
packages=("${files[@]/%.py/}")
nosetests --with-coverage "${packages[@]/#/--coverage-package=}"



回答3:


nosetests --with-coverage `ls *.py|sed -e 's/^/--cover-package=' -e 's/\.py$//'`


来源:https://stackoverflow.com/questions/855265/how-do-i-write-some-bash-shell-script-to-convert-all-matching-filenames-in-dir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!