Home > Blockchain >  Carriage return in a bash variable
Carriage return in a bash variable

Time:11-17

I have a bash variable that ends with \r\n:

$ # Not the real command to get VAR's value, just an example
$ VAR="$(echo -en 'hello\r\n')"
$ hexdump -C <<< "$VAR"
00000000  68 65 6c 6c 6f 0d 0a                              |hello..|
00000007

I would like to drop the \r (the \n itself is correctly handled by bash).

I may trim it (VAR="$(tr -d '\r' <<< "$VAR")"), but that implies to run a process just for that task.

I tried using "Remove matching suffix pattern" bash feature, but cannot find which pattern to use (e.g., ${VAR%\r}, ${VAR%\x0d}, ${VAR%[\r]}—but neither of them does work).

Any idea how to drop the \r without creating a subprocess?

CodePudding user response:

Use the ANSI C quotes. With substitution, use

var=${var//$'\r'}

If you want to only remove the \r before the final \n, you can use

var=${var%$'\r\n'}$'\n'

i.e. you have to remove both the \r and \n, so you need to add the \n back.

  • Related