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.
You can escape your
\characters so they are still present in yourread line, like this: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
-rparameter to thereadcommand, it instructs it to don’t escape the slashes, so this would also work: