在Makefile中使用sed用变量

时间:2017-01-22 06:46:05

标签: bash variables sed makefile

我进行了广泛的搜索,发现了很多类似的问题,但据我所知,没有找到实际做到我想要的问题。

以下是最近的问题:Using sed in a makefile; how to escape variables?

我想在Makefile中做的非常简化的版本是

sed s~foo~${BAR}~

其中$BAR是我的makefile中的变量。显然,我想将foo替换为$BAR,而不是使用当前正在发生的文本${BAR}

自提出要求以来,这里是完整版本:
注意,目标是让Makefile成为POSIX。

Makefile(仅限相关部分):

...
diff:
    scripts/build/diff-all.sh
...

脚本/建造/ diff-all.sh

#!/bin/bash -e

for DIFFBRANCH in $(cat diff-branches); do
    scripts/build/diff.sh $DIFFBRANCH
done

DIFF-分支

2016_reorg_diff
# more branches here

脚本/建造/ diff.sh

#/bin/bash -e

DIFFBRANCH=$1
BRANCH=$(git rev-parse --abbrev-ref HEAD)
CHAPTERDIR=src/chapters
SHORTCHAPTERDIR=${CHAPTERDIR##src/} # remove src/ from the start of CHAPTERDIR
CHAPTERS=$(ls $CHAPTERDIR | grep "^\\d\\d_.*\\.tex$")

LATEXARGS="-file-line-error -halt-on-error"

if [[ ! $DIFFBRANCH ]]; then
    echo "usage: $0 DIFFBRANCH"
    exit 1
fi

mkdir -p tmp
mkdir -p pdf

for CHAPTER in $CHAPTERS; do # make tex diff files for each chapter
    SLUG=$(echo $CHAPTER | cut -f 1 -d '.')
    latexdiff-vc --git --so --flatten  --force -r $DIFFBRANCH -r $BRANCH $CHAPTERDIR/$CHAPTER
    mkdir -p tmp/$CHAPTERDIR
    mv -v $CHAPTERDIR/$SLUG-diff$DIFFBRANCH-$BRANCH.tex tmp/src_diff_$DIFFBRANCH/$SHORTCHAPTERDIR/$SLUG-$BRANCH-diff-$DIFFBRANCH.tex
done

rsync -avz --exclude $SHORTCHAPTERDIR src/ tmp/src_diff_$DIFFBRANCH/ # copy all source files to tmp except chapters (because they're already there)

sed -i.bak -E 's~^([[:blank:]]*\subimport{chapters/}{[[:alnum:]_]+)}~\1-$BRANCH-diff-$DIFFBRANCH}~' tmp/src_diff_$DIFFBRANCH/iuf-rulebook.tex 
# this replaces \subimport{chapters/}{01_general} with \subimport{chapters/}{01_general-$BRANCH-diff-$DIFFBRANCH} with the variables expanded
# so that the iuf-rulebook.tex uses the diffed chapters
# the -i.bak is required so SED works on OSX and Linux
rm -f tmp/src_diff_$DIFFBRANCH/*.bak # because of this, we have to delete the .bak files after


mkdir -p tmp/out_diff_$DIFFBRANCH
TEXINPUTS=tmp/src_diff_$DIFFBRANCH: latexmk -pdf $LATEXARGS -quiet -output-directory=./tmp/out_diff_$DIFFBRANCH tmp/src_diff_$DIFFBRANCH/iuf-rulebook.tex
mv tmp/out_diff_$DIFFBRANCH/iuf-rulebook.pdf pdf/iuf-rulebook-$BRANCH-diff-$DIFFBRANCH.pdf
rm -rf tmp/*_$DIFFBRANCH

1 个答案:

答案 0 :(得分:0)

命令:

sed -e s/number/$(BAR)/g 

验证:

VAR = random number
VAR1 = file
FOO = $(VAR)
$(info before substitution: $(FOO))
FOO = $(shell echo $(VAR) | sed -e s/number/$(VAR1)/g )
$(info after substitution: $(FOO))