1

I have several files in a single folder and I want to replace the character > with >\n everywhere in all of those files.

But whatever I do, the \n character does not get added after the > character.

I have tried the following:

echo '>ABCCHACAC' | tr '\>' '>\\n'
echo '>ABCCHACAC' | tr '>' '>\\n'
echo '>ABCCHACAC' | tr '>' '>\n'
echo '>ABCCHACAC' | tr '>' '\>\n'
echo '>ABCCHACAC' | tr '>' '\>\\n'
echo '>ABCCHACAC' | tr '>' '\>\\n'

But I get the same input string as output, whereas the correct output I want is:

>
ABCCHACAC

And I am using this script to do the same thing on many files:

for f in *.txt
do
  tr ">" ">\n" < "$f" > $(basename "$f" .txt)_newline_added.txt
done
votresignu
  • 71
  • 4

2 Answers2

3

tr is for one-for-one character replacements, not replacing strings. E.g. if you translate abc with def, it replaces all a with d, all b with e, and all c with f. When the second string is longer than the first, the extra characters are ignored. So tr '>' '>\n' means to replace > with > and ignores \n.

Use sed to perform string replacements.

sed 's/>/>\n/g' "$f" > "$(basename "$f" .txt)_newline_added.txt"
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Great answer. Exactly what I was looking for. I only think that you missed a crucial, third delimiter (that is, `/`) at the end of your sed expression right after `\n` inside the quotation marks. Therefore, the correct expression would be: `sed 's/>/>\n/'` – votresignu Feb 12 '18 at 21:24
  • 1
    @votresignu Right, I also forgot the `g` modifier to do multiple replacements per line. – Barmar Feb 12 '18 at 21:30
  • Would the `g` be essential if I have only and only one `>` character per each line? – votresignu Feb 12 '18 at 21:46
  • No, but there's nothing in the question that suggests this constraint on the input file. – Barmar Feb 12 '18 at 21:49
0

In addition to Barmar's answer, if you're using a BSD based *nix (eg. OS X) you'll either need to include an escaped literal newline, or possibly use tr in addition to sed.

Escaped literal newline:

$ sed 's/^>/>\
/' "$f"

sed with tr:

$ sed 's/^>/>▾/' "$f" | tr '▾' '\n'

Insert newline (\n) using sed

l'L'l
  • 44,951
  • 10
  • 95
  • 146