Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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).

share|improve this question
up vote 6 down vote accepted

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
share|improve this answer

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
share|improve this answer

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}"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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