krb686
krb686

Reputation: 1796

Trying to search and replace newline ("\n") with newline and tab ("\n\t") in sed

I have a block of text I'm trying to edit like this, in a script:

First, I tried

VAR2=`echo $VAR | sed 's/\n/\n\t/g'

It removes the newlines, but doesn't add the newline or tab back in.

Is this some stupid mistake? Not escaping something I should?

Upvotes: 0

Views: 603

Answers (1)

Wintermute
Wintermute

Reputation: 44043

Two things:

  1. You have to prevent shell expansion of $VAR, or the newlines will be lost before you have a chance to handle them
  2. sed works in a line-based manner. It treats every line individually, and it doesn't see the newlines between them (unless you do special things).

The first can be handled by quoting $VAR, the second problem I would circumvent by reformulating the problem as "insert a tab to the beginning of every line but the first." That leaves us with:

VAR2=$(echo "$VAR" | sed '1!s/^/\t/')

Where the sed code means: Under the condition 1! (which is the case when we're not handling the first line), do s/^/\t/ -- i.e., replace the empty string at the beginning of the line with a tab.

Note that to look at the result of the substitution, you'll have to quote it as well, or it'll be shell-expanded, and the inserted whitespaces will be lost. That is to say,

echo "$VAR2"

will show the result you want, while

echo $VAR2

will lose all formatting (and potentially do silly things, if there are special characters such as $ in the paragraph).

Upvotes: 2

Related Questions