Replace a string in a string with a new line (\n) in Bash
Use ANSI C style escape sequence $'\n'
to indicate newline:
$ string=xyababcdabababefab
$ echo "${string/abab/$'\n'}"
xy
cdabababefab
Or use zsh
to use just \n
:
% string=xyababcdabababefab
% echo "${string/abab/\n}"
xy
cdabababefab
You should use -e
with echo
as follows:
echo -e ${string/abab/'\n'}
From manpage:
-e enable interpretation of backslash escapes
If -e is in effect, the following sequences are recognized:
\\ backslash
\a alert (BEL)
\b backspace
\c produce no further output
\e escape
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
In addition to above use newline by itself:
echo "${string/abab/
}"
note the quoting to avoid \n
ewline substitution by space
For old bash version can be suitable:
printf "%s\n" "${string%%abab*}" "${string#*abab}"