Problem :
I have always been able while looping through characters to identify the char I want. However, now that I want to identify a carriage return, my way of doing things doesn't seem to work :
function removeCarriageReturn()
{
word=""
while IFS= read -r -n1 char ; do
if [ "${char}" != "\r" ] ; then
word="${word}${char}"
fi
done <<<"$1"
printf '%s\n' "$word"
}
Result :
For a reason I don't know, it adds a "$" in front of the carriage return, why? Here is the result (from Jenkins) :
When char analysed is for example 8
++ '[' 8 '!=' '\r' ']'
When char analysed is \r
++ '[' $'\r' '!=' '\r' ']'
$''
quoting is ANSI-C quoting and it interprets some escape sequences.
Nothing is being added there that's just set -x
showing you what is actually happening. You don't have the two-character string "\r"
you have a literal \r
and that's what $'\r'
is.
This fact (and the set -x
output) also tell you how to match the character you are looking for. Use $'\r'
.
Sidestepping your actual question, the easiest way to remove any carriage returns from a value is
value=${value//$'\r'}
(which also demonstrates that your if
statement would read
if [ "$char" != $'\r' ]; then.
Note that this is the same syntax that -x
is using to display the carriage return.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With