通过将路径从unix更改为windows,将第一行文件替换为另一行

时间:2012-03-03 14:24:25

标签: bash

我正在尝试执行一个bash脚本:

  • 循环浏览一些文件:确定
  • 检查第一行是否与此模式匹配(#!f:\ test \ python.exe):确定
  • 通过将unix样式更改为Windows样式来创建新路径:KO

准确地说, 来自:\ c \ tata \ development \ tools \ virtualenvs \ test2 \ Scripts \ python.exe 我想得到:c:\ tata \ development \ tools \ virtualenvs \ test2 \ Scripts \ python.exe

  • 通过附加#来插入新行!和新路径:KO

跟随我的剧本,但我真的被卡住了!

for f in $WORKON_HOME/$env_name/$VIRTUALENVWRAPPER_ENV_BIN_DIR/*.py
    do
        echo "----"
        echo file=$f >&2

        FIRSTLINE=`head -n 1 $f`        
        echo firstline=$FIRSTLINE >&2

        unix_path=$WORKON_HOME/$env_name/$VIRTUALENVWRAPPER_ENV_BIN_DIR/python.exe
        new_path=`echo $unix_path | awk '{gsub("/","\\\")}1'`       
        echo new_path=$new_path >&2

        # I need to change the new_path by removing the first \ and adding : after the first letter => \c -> c:

        new_line="#!"$new_path
        echo new_line=$new_line >&2

        case "$FIRSTLINE" in 
         \#!*python.exe* )
            # Rewrite first line
            sed -i '1s,.*,'"$new_line"',' $f
        esac        
    done

输出:

file=/c/tata/development/tools/virtualenvs/test2/Scripts/pip-script.py
firstline=#!f:\test\python.exe
new_path=\c\tata\development\tools\virtualenvs\test2\Scripts\python.exe
new_line=#!\c\tata\development\tools\virtualenvs\test2\Scripts\python.exe

写在文件中的行:(写了一些奇怪的字符,我不知道为什么......)

#!tatadevelopment   oolsirtualenvs  est2Scriptspython.exe

我期待的行:

#!c:\tata\development\tools\virtualenvs\test2\Scripts\python.exe

1 个答案:

答案 0 :(得分:2)

sed正在将反斜杠和后面的字符解释为转义符,所以你得到了,例如标签。你需要逃避反斜杠。

sed -i "1s,.*,${new_line//\\/\\\\}," "$f"