-1

Reference: How to remove a newline from a string in Bash

I feel a little silly asking this, but when I'm solving a problem, I like to learn about the WHY instead of just copying-and-pasting code I found on the Internet. :-)

I've been reading this and the bash man pages and, for the life of me, I cannot identify in the documentation where this is valid syntax. However, I run it and it works.

To test, I ran:

[me@server ~]# declare -- MY_VAR="some value
> "

This creates a variable with \n at the end (i.e. "some value\n").

My goal is to remove the \n at the end.

I know the following code will do it:

echo ${MY_VAR//[$'\n']}

... what I don't know is WHY.

I've read Shell Parameter Expansion and the section on ${parameter/pattern/string}. I've also read the referenced section, Pattern Matching. Neither tells me that having a dollar sign ($) as the first character in, what I believe to be, a character group ([...]), has any special meaning or what that meaning is. Also, why does \n need to be enclosed in single-quotes?

I also tried the following variations of the above working command and none of them work:

echo ${MY_VAR//['\n']}
echo ${MY_VAR//[$]}
echo ${MY_VAR//['\n'$]}
echo ${MY_VAR//[\n]}
echo ${MY_VAR//[$\n]}
echo ${MY_VAR//['$\n']}

Can anyone point me in the direction of documentation that can tell me why I need to use the dollar sign ($) and why the \n needs to be enclosed in single-quotes?

Hossy
  • 139
  • 1
  • 2
  • 11

1 Answers1

0

I just found the answer to my own question: ANSI-C Quoting

$'string' is treated specially. What I believe is happening is that this $'string' is being used to pass the special newline character (as well as the tab and carriage return characters in the other post I referenced) back into the character group.

Credit: https://unix.stackexchange.com/questions/48106/what-does-it-mean-to-have-a-dollarsign-prefixed-string-in-a-script

Hossy
  • 139
  • 1
  • 2
  • 11