1

On using the command:

tr -s '\n' ' '< test1

where test1 is a text file.

If test1 is written in a manner such that it contains newlines (linefeed characters) and not \n (backslash-n) then the answer comes as expected that is all the newlines get replaced by a single space.

But if say the test1 is formatted such that it contains \n (backslash-n) and not a newline then running the command the \n does not get replaced by a single space, E.g. if test1 contains

hello \n\n\n how are \n\n you

then the output is

hello \n\n\n how are \n\n you

and not

hello   how are   you
codelec
  • 11
  • \n should be "code" for the actual newline character. backslash n is just two regular ascii characters... tr doesn't work on strings of 2 or more characters – Xen2050 Dec 21 '14 at 18:17

1 Answers1

2

So is the question how does one substitute literal backslash-n's?

If so, it can't be done with tr, since tr only works on single characters. Here's how to do it in sed (string editor):

$ cat test1
hello \n\n\n how are \n\n you
$ sed -e 's/\\n/ /g' < test1
hello     how are    you

note the extra backslash needed to tell sed we're looking for a literal backslash here, and to not interpret '\n' as a line feed character.

  • So tr can not translate a string of 2 characters – Xen2050 Dec 21 '14 at 18:18
  • @Xen2050 tr can translate strings of any length... as long as an ordering is not required. – muru Dec 21 '14 at 18:28
  • @muru Is it really still what's commonly known as a "string" if the order doesn't matter? I'm thinking of "words" for example. But I don't think I'll ever figure out tr, when these two commands are equivalent it's time to get the cheque & leave tr aaa xyz and tr a z – Xen2050 Dec 21 '14 at 18:39
  • @Xen2050 tr uses sets of characters (which is why ordering is ignored in input). When you specify a multiple times, tr only sees a single character in the first set. – muru Dec 21 '14 at 18:42