python脚本上的sed替换 - "命令未找到"问题

时间:2017-04-09 12:06:14

标签: python bash sed

我已经谷歌搜索了一段时间但找不到答案。我有以下bash函数,它在python项目目录中为grep执行'NAME'。它会选择包含'NAME'的正确文件。然后我运行sed命令用'NAME'替换用户输入字符串。

replace_NAME_in_files() {
    read -ra MATCHED_FILES <<< `grep 'NAME' $NEW_PROJECT -lR`
    for file in "${MATCHED_FILES[@]}"; do
        `sed "s/NAME/$1/g" $file`
    done
}

我得到的错误如下:

/Users/me/scripts/new_python_project.sh: line 37: try:: command not found
from: can't read /var/mail/nose.tools

现在,与grep 'NAME'匹配的2个文件如下所示:

Dev-MacBook-Pro:projects dev$ cat ex47/setup.py 
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
        'description': 'My Project',
        'author': 'Dev',
        'url': 'URL to get it at.',
        'download_url': 'Where to download it.',
        'author_email': 'My email.',
        'version': '0.1',
        'install_requires': ['nose'],
        'packages': ['NAME'],
        'scripts': [],
        'name': 'projectname'
}

setup(**config)

sed的另一个输入文件是:

Dev-MacBook-Pro:projects dev$ cat ex47/tests/ex47_tests.py 
from nose.tools import *
import NAME

def setup():
    print "SETUP!"

def teardown():
    print "TEAR DOWN!"

def test_basic():
    print "I RAN!"

当我使用调试模式运行脚本时,输出为:

++ grep NAME /Users/dev/python/workspace/projects/ex47 -lR
+ for file in '"${MATCHED_FILES[@]}"'
++ sed s/NAME/ex47/g /Users/dev/python/workspace/projects/ex47/setup.py
+ try: from setuptools import setup except ImportError: from distutils.core import setup config = '{' ''\''description'\'':' ''\''My' 'Project'\'',' ''\''author'\'':' ''\''dev'\'',' ''\''url'\'':' ''\''URL' to get it 'at.'\'',' ''\''download_url'\'':' ''\''Where' to download 'it.'\'',' ''\''author_email'\'':' ''\''My' 'email.'\'',' ''\''version'\'':' ''\''0.1'\'',' ''\''install_requires'\'':' '['\''nose'\''],' ''\''packages'\'':' '['\''ex47'\''],' ''\''scripts'\'':' '[],' ''\''name'\'':' ''\''projectname'\''' '}' 'setup(**config)'
/Users/dev/scripts/new_python_project.sh: line 37: try:: command not found
+ for file in '"${MATCHED_FILES[@]}"'
++ sed s/NAME/ex47/g /Users/dev/python/workspace/projects/ex47/tests/ex47_tests.py
+ from nose.tools import ex47 skeleton skeleton_bck import ex47 def 'setup():' print '"SETUP!"' def 'teardown():' print '"TEAR' 'DOWN!"' def 'test_basic():' print '"I' 'RAN!"'
from: can't read /var/mail/nose.tools

sed似乎做了替换,但是它出现了,因为它试图执行输入文件?知道发生了什么吗?

1 个答案:

答案 0 :(得分:1)

尝试取出后面的刻度并使用sed&#39; s / NAME / $ 1 / g&#39; &#34; $文件&#34;

后面的滴答声看到间接,因此它试图在sed命令之后执行$ file而不是将它与sed一起使用。