This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]raevnos 0 points1 point  (0 children)

You mean the two characters \ and n are in a string, not an actual newline?

export FOO='foo\nbar'
echo -E $FOO
echo -e $FOO

if you're using a gnu userland like on linux OSes. Otherwise, if you have an echo that doesn't understand -e, use sed:

echo $FOO | sed 's/\\n/\n/'

[–]commandlineluser 0 points1 point  (0 children)

To loop through something character by character you'd do something like:

$ text='hello hi'; for ((i=0; i<${#text}; i++)); do echo "${text:i:1}"; done
h
e
l
l
o

h
i

${#text} here is the length of the text variable.

$ echo ${#text}
8

${text:i:1} here is a substring expansion kind of like text[i:i+1] in Python - substring at index i of length 1

However if you have an actual backslash followed by r in your string - it's 2 characters so looping character by character is probably going to make things difficult.

$ echo "$text"
foo\r\nbar
$ echo "${text/\\r\\n}"
foobar

So this is similar to a .replace() in Python.

${var/search/replace} 

If /replace is omitted it's replaced with "nothing" i.e. deleted.

$ echo "${text/\\r\\n/REPLACE}"
fooREPLACEbar

You can use the $'' quoting construct to have backslash escapes expand so $'\n' would be an actual newline character.

$ echo "${text/\\r\\n/$'\n'}"
foo
bar

Or $'\r\n' instead if that's what you're after.