Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know if a character is a carriage return?

Tags:

bash

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' ']'
like image 835
Cher Avatar asked Jan 09 '23 00:01

Cher


2 Answers

$'' 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'.

like image 166
Etan Reisner Avatar answered Jan 19 '23 00:01

Etan Reisner


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.)

like image 36
chepner Avatar answered Jan 18 '23 23:01

chepner