Bash: How can I replace a string by new line in osx bash?

13,715

Solution 1

Here is using 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 blogpost explaining why - https://nlfiedler.github.io/2010/12/05/newlines-in-sed-on-mac.html

Solution 2

Using bash only:

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 quick explanation here - the syntax is similar to sed's replacement syntax, but you use a double slash (//) to indicate replacing all instances of the string. Otherwise, only the first occurrence of the string is replaced.

Solution 3

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 doesn't 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

Yet 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
Share:
13,715
Rodrigo
Author by

Rodrigo

I am actualy working for Banco do Brasil, building the app programs in Objective-C.

Updated on June 26, 2022

Comments

  • Rodrigo
    Rodrigo almost 2 years

    I am googling it a lot. I only want that 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't use sed for this? Is there another one line solution?