如何读取文件并将替换应用于其内容?

How to read file and apply substitutions to its content?

我有一个很长的字符串,我想将其提取到一个单独的文件中。

prepare = lib.hm.dag.entryAfter ["writeBoundary"] '' very long script with ${...} '';

我可以用 builtins.readFile 阅读它,但它不会替换 ${...} nix 占位符。

如何从文件中读取字符串并解析其中的 nix 变量?

您可以使用 bash 函数的 substitute 系列(参见 Nixpkgs manual)或使用 substituteAll Nix 函数,该函数生成执行替换的推导。

substituteAll { src = ./sample.sh; inherit bash; hi = hello; }

sample.sh:

#!@bash@/bin/bash
@hi@

结果:

$ nix repl <nixpkgs>

nix-repl> substituteAll { src = ./sample.sh; inherit bash; hi = hello; }
«derivation /nix/store/7klv763a0ipgvwf3j84aazkzx2d5rljz-sample.sh.drv»

nix-repl> :b substituteAll { src = ./sample.sh; inherit bash; hi = hello; }

this derivation produced the following outputs:
  out -> /nix/store/v03hpzw9ykrbyqpmalnijnyibq3waqhw-sample.sh

nix-repl> 

/nix/store/v03hpzw9ykrbyqpmalnijnyibq3waqhw-sample.sh:

#!/nix/store/a4yw1svqqk4d8lhwinn9xp847zz9gfma-bash-4.4-p23/bin/bash
/nix/store/jmmw0d3nmklwafcwylvrjb9v69wrbcxf-hello-2.10