Remove trailing newline from esyscmd in m4

1.9k views Asked by At

I'm using m4 to create some basic macros and I realize that when using esyscmd there's a trailing new line added to a string when the command is run.

Example:

define(MY_HOSTNAME, esyscmd(`hostname'))
MY_HOSTNAME
Some other text...

Renders:

> my.host.name
>
> Some other text...

(complete with a trailing new line)

By adding dnl at the end of the define (or esyscmd) nothing appears to happen and there's still a trailing newline.

What's the best way to drop the trailing newline when calling esyscmd in m4?

4

There are 4 answers

0
devnull On BEST ANSWER

*nix systems have tr by default. Make use of that:

define(MY_HOSTNAME, esyscmd(sh -c "hostname | tr -d '\n'"))

and you'd get rid of the trailing newline!

1
AudioBubble On

devnull's example is good but, M4 has a builtin tr as well. Here's what I'm doing:

define(CMD_OUTPUT, esyscmd(`sass --style=compressed foo.sass'))
define(NL,`
')
translit(CMD_OUTPUT, NL)

Someone a little better with M4 could tighten that into a single macro.

0
Shammel Lee On

You can use the translit macro. If no third argument is passed, the list of characters passed in the second argument are deleted from the first argument. So in your case, your first argument to translit would be esyscmd(`hostname'), the second argument would be the newline character, and you would not pass a third argument. Note: the literal newline character below causes the macro definition to be on two lines:

define(`MY_HOSTNAME', translit(esyscmd(`hostname'), `
'))dnl

foo MY_HOSTNAME bar  # -> foo Dans-Macbook-Pro.local bar
1
Wrikken On

An alternative would be

echo -n `hostname`

No pipe, but backticks, whatevers suits your fancy.