13

How do i replace the \r?

#!/bin/bash
...

# setup
if [[ $i =~ $screen ]]; then

    ORIGINAL=${BASH_REMATCH[1]}          # original value is: 3DROTATE\r
    AFTER   =${ORIGINAL/\\r/}            # does not replace \r
    myThirdPartyApplication -o $replvar  # FAILS because of \r

fi
rid
  • 61,078
  • 31
  • 152
  • 193

5 Answers5

25

This should remove the first \r.

AFTER="${ORIGINAL/$'\r'/}"

If you need to remove all of them use ${ORIGINAL//$'\r'/}

tharrrk
  • 361
  • 1
  • 3
  • 3
  • 1
    IMHO this is the best answer, as it avoids the overhead of launching an external program (such as sed or tr). The $ at the beginning of $'\r' is essential to have the \r converted to a 'carriage return' character in the pattern of things to be replaced. Maybe it's not obvious, the \r is replaced with nothing (the absence of characters between the last / and }. – Tim Bird Jan 11 '17 at 01:52
  • this maybe a top voted answer and works for me too. but there is a problem reported by shellcheck: https://github.com/koalaman/shellcheck/wiki/SC3060 – Mohammad Faisal Dec 13 '21 at 17:37
11

You could use sed, i.e.,

AFTER=`echo $ORIGINAL | sed 's/\\r//g'`
imm
  • 5,837
  • 1
  • 26
  • 32
5

Another option is to use 'tr' to delete the character, or replace it with \n or anything else.

 ORIGINAL=$(echo ${BASH_REMATCH[1]} | tr -d '\r')
3molo
  • 206
  • 2
  • 7
3

Similar to @tharrrk's approach, this parameter substitution also remove the last '\r':

AFTER="${ORIGINAL%'\r'}"
user2510797
  • 43
  • 1
  • 3
  • 11
3

Just use a literal ^M character, it has no meaning to bash.

Neil
  • 54,642
  • 8
  • 60
  • 72