In BASH, How do i replace \r from a variable that exist in a file written using HTML <textarea></textarea>
Asked Answered
P

5

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
Preponderance answered 17/10, 2011 at 22:42 Comment(1)
can't have spaces around the =Eisk
E
11

You could use sed, i.e.,

AFTER=`echo $ORIGINAL | sed 's/\\r//g'`
Electroluminescence answered 17/10, 2011 at 22:48 Comment(2)
It drops $' in the beginning also. Cool.Phenomenon
Worked!!! Just a little improve: spaces are not allowed in value assignation : AFTER=echo...Harbor
L
25

This should remove the first \r.

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

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

Lunation answered 25/4, 2013 at 7:43 Comment(2)
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 }.Windhover
this maybe a top voted answer and works for me too. but there is a problem reported by shellcheck: github.com/koalaman/shellcheck/wiki/SC3060Chivaree
E
11

You could use sed, i.e.,

AFTER=`echo $ORIGINAL | sed 's/\\r//g'`
Electroluminescence answered 17/10, 2011 at 22:48 Comment(2)
It drops $' in the beginning also. Cool.Phenomenon
Worked!!! Just a little improve: spaces are not allowed in value assignation : AFTER=echo...Harbor
T
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')
Tamatave answered 10/6, 2013 at 13:16 Comment(0)
V
3

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

Vav answered 17/10, 2011 at 22:48 Comment(0)
I
3

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

AFTER="${ORIGINAL%'\r'}"
Isfahan answered 8/10, 2013 at 0:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.