Pergunta

I am using this snippet to read a variable line by line:

echo "${lines}" | while read line; do something with ${line}; done

lines contains new lines and occurrences of the \ character (the line will be interpreted as a C string). Unfortunately, somewhere in this code the \ characters are simply stripped. Why, and how do I fix that?

EDIT: a sample input is this:

foo $'bar'
fee $'ber\fbir'

note that only the \ is stripped, not the $'' which will be used later to interpret the string as a C string.

Foi útil?

Solução

You can escape your \ characters so they are still present in your read line, like this:

echo "${lines}" | sed 's/\\/\\\\/g' | while read line; do something with ${line}; done

UPDATE: I've just updated the sed line above after some testing, try it now, it's working for me.

UPDATE 2: As it seems jordanm deleted his answer which was using a better approach than mine, I'll add it here myself:

Using the -r parameter to the read command, it instructs it to don't escape the slashes, so this would also work:

echo "${lines}" | while read -r line; do something with ${line}; done
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top