Sed

無法讓 sed 使用變數和引號

  • August 25, 2022

我即將編寫一個 shell 腳本來替換這一行:

exec "$progdir/$program" ${1+"$@"}

和:

exec qemu-arm -L /mnt/c/git/build/linux_arm7/build_arm7/sysroot "$progdir/$program" ${1+"$@"}

在一個文件中。 /mnt/c/git/build/linux_arm7/build_arm7現在在一個名為BUILD_DIRECTORY. 無論我嘗試了什麼(引號,不同的分隔符),我總是以變數而不是替換結束。例如我試過這個:

#!/bin/bash
sed_test()
{
   sed -i 's|exec "\$progdir\/\$program" \${1+"\$@"}|exec qemu-arm -L ${BUILD_DIRECTORY}\/sysroot "\$progdir\/\$program" \${1+"\$@"}|g' ${BUILD_DIRECTORY}/file
}

並在文件中得到了這個:

exec qemu-arm -L ${BUILD_DIRECTORY}/sysroot "$progdir/$program" ${1+"$@"}

如何正確執行此操作?

  • 引用防止${BUILD_DIRECTORY}變數擴展
  • g不需要final
  • 你逃脫了很多

如果 BUILD_DIRECTORY 變數中沒有空格,請使用

sed -i 's|exec "$progdir/$program" ${1+"$@"}|exec qemu-arm -L '${BUILD_DIRECTORY}'/sysroot "$progdir/$program" ${1+"$@"}|'  ${BUILD_DIRECTORY}/file

注意單引號${BUILD_DIRECTORY}

如果 BUILD_DIRECTORY 中有空間(比如說linux arm7),請使用中繼字元串(命令拆分)

sed -e 's|exec "$progdir/$program" ${1+"$@"}|exec qemu-arm -L BUILD_DIRECTORY/sysroot "$progdir/$program" ${1+"$@"}|'  
  -e "s|BUILD_DIRECTORY|${BUILD_DIRECTORY}|" 
  "${BUILD_DIRECTORY}/file"

屈服

exec qemu-arm -L /mnt/c/git/build/linux arm7/build_arm7/sysroot "$progdir/$program" ${1+"$@"}

引用自:https://unix.stackexchange.com/questions/714847