From 78f5eb399e454c7fc3d3f0acec07cdc12b405031 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20Mass=C3=A9?= Date: Fri, 15 Mar 2019 15:08:39 +0100 Subject: [PATCH] 2019-03-15 update --- content/blog/m4-as-replacement-for-sed.md | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 content/blog/m4-as-replacement-for-sed.md diff --git a/content/blog/m4-as-replacement-for-sed.md b/content/blog/m4-as-replacement-for-sed.md new file mode 100644 index 0000000..c84b4f1 --- /dev/null +++ b/content/blog/m4-as-replacement-for-sed.md @@ -0,0 +1,45 @@ +--- +title: "M4 as a replacement for sed" +date: 2019-03-15T00:00:00+02:00 +--- + +Writing a tutorial often involves to replace a placeholder in a file, such as: + +*Replace FOO with the actual name of your image:* + +```sh +sed 's|IMAGE_NAME|docker.io/foo/bar:latest|g' template.yaml |kubectl apply -f - +``` + +But this approach has several drawbacks: + +- If you have to replace multiple placeholders, the sed syntax becomes cumbersome. +- If the delimiter appears in your replacement string, you will have to find another + delimiter (such as in the previous example where the usual slash has been replaced + by a pipe to accomodate the slash in the image name). +- The `sed` command has some subtleties between the GNU (any Linux distribution) + and the BSD (MacOS) flavors. + +For this specific use case (replacing placeholders), I would like to introduce +another tool: the `m4` command. + +The `m4` command is used in the C/C++ compilation chain to replace pre-processor +directives with their actual values. Its syntax is very simple and it is present on +most Linux distributions and on MacOS by default. + +Let's have a look at a very simple example: + +```raw +$ cat > example <