it by N...">

Bash: How to replace a string with a new string in osx bash?

I walk a lot on it. I only need this line:

echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed -e 's/<newLine>/\n/g' 

works in my osx terminal and in my bash script. I can not use sed for this? Is there another linear solution?

+7
source share
3 answers

It uses sed

 echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed 's/<newLine>/\'$'\n/g' 

And here is a blog post explaining why - https://nlfiedler.imtqy.com/2010/12/05/newlines-in-sed-on-mac.html

+18
source

Only bash:

 STR="Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" $ echo ${STR//<newLine>/\\n} Replace \n it by \n NEWLINE \n in my OSX terminal \n and bash script $ echo -e ${STR//<newLine>/\\n} Replace it by NEWLINE in my OSX terminal and bash script 

A brief explanation here is that the syntax is similar to the sed replacement syntax, but you use a double slash ( // ) to indicate that all instances of the string are replaced. Otherwise, only the first occurrence of the string is replaced.

+4
source

This might work for you:

 echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed 'G;:a;s/<newLine>\(.*\(.\)\)$/\2\1/;ta;s/.$//' Replace it by NEWLINE in my OSX terminal and bash script 

EDIT: OSX does not accept multiple commands, see here

 echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed -e 'G' -e ':a' -e 's/<newLine>\(.*\(.\)\)$/\2\1/' -e 'ta' -e 's/.$//' Replace it by NEWLINE in my OSX terminal and bash script 

Another way:

 echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed $'s|<newLine>|\\\n|g' Replace it by NEWLINE in my OSX terminal and bash script 
+1
source

All Articles