6

I tried this command:

[silas@mars 11]$ string=xyababcdabababefab
[silas@mars 11]$ echo ${string/abab/"\n"}
xy\ncdabababefab
[silas@mars 11]$

I also tried to replace "\n" to '\n' and to \n . I can't use AWK or sed (this is a part from a homework exercise, and the teacher don't allow to use in this specific exercise).

9

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
13

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
7

In addition to above use newline by itself:

echo "${string/abab/
}"

note the quoting to avoid \newline substitution by space
For old bash version can be suitable:

printf "%s\n" "${string%%abab*}" "${string#*abab}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.