Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing newline from esyscmd in m4

Tags:

bash

shell

m4

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?

like image 744
Dan Avatar asked Dec 18 '13 01:12

Dan


4 Answers

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
like image 187
Shammel Lee Avatar answered Nov 08 '22 02:11

Shammel Lee


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.

like image 43
jdeseno Avatar answered Nov 08 '22 04:11

jdeseno


*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!

like image 3
devnull Avatar answered Nov 08 '22 04:11

devnull


An alternative would be

echo -n `hostname`

No pipe, but backticks, whatevers suits your fancy.

like image 2
Wrikken Avatar answered Nov 08 '22 04:11

Wrikken