Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new line in bash parameter substitution ${REV%%\n*}

Tags:

bash

does not work

echo ${REV%%\n*}

does work

echo ${REV%%
*}

After reading trough http://tldp.org/LDP/abs/html/parameter-substitution.html I still can not figure out how to make \n work.

like image 918
Gert Cuykens Avatar asked Aug 20 '11 01:08

Gert Cuykens


People also ask

How do I add a new line to a string in bash?

Printing Newline in Bash Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.

What is parameter substitution in bash?

The length in characters of the expanded value of parameter is substituted. If parameter is ' * ' or ' @ ', the value substituted is the number of positional parameters. If parameter is an array name subscripted by ' * ' or ' @ ', the value substituted is the number of elements in the array.


2 Answers

${REV%%$'\n*'} seems to work. See the quoting section of the bash documentation.

like image 54
hobbs Avatar answered Sep 23 '22 18:09

hobbs


If your intent is to try and get it on one line and you're willing to go "outside" of bash, you can use:

echo "$(echo "${REV}" | head -1l)"

But, assuming your version of bash is recent enough, you can try:

pax> export REV="abc
...> def"

pax> echo "${REV}"
abc
def

pax> echo "${REV%%$'\n'*}"
abc

The reason you need $'\n' is because the bash definition of word is somewhat restrictive, compared to what you expect. The bash manpage has this to say:


Words of the form $'string' are treated specially. The word expands
to string, with backslash-escaped characters replaced as specified by
the ANSI C standard. Backslash escape sequences, if present, are decoded
as follows:
   \a     alert (bell)
   \b     backspace
   \e
   \E     an escape character
   \f     form feed
   \n     new line
   \r     carriage return
   \t     horizontal tab
   \v     vertical tab
   \\     backslash
   \'     single quote
   \"     double quote
   \nnn   the eight-bit character whose value is the octal value
          nnn (one to three digits)
   \xHH   the eight-bit character whose value is the hexadecimal
          value HH (one or two hex digits)
   \uHHHH the Unicode (ISO/IEC 10646) character whose value is
          the hexadecimal value HHHH (one to four  hex  digits)
   \UHHHHHHHH
          the  Unicode  (ISO/IEC 10646) character whose value is
          the hexadecimal value HHHHHHHH (one to eight hex digits)
   \cx    a control-x character
like image 26
paxdiablo Avatar answered Sep 22 '22 18:09

paxdiablo