简体   繁体   中英

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

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM