4

I saw this: How can I replace a newline (\n) using sed?, and figured I would try to use tr to replace newlines with ',.

The file looks like this:

something
newline
newline again

and I want it to look like this:

something',
newline',
newline again',

So, I tried these:

tr "\n" "'," < myfileabove tr "\n" "\'," < myfileabove

Neither of them does what I'd like....am I doing something wrong?

Community
  • 1
  • 1
makansij
  • 9,303
  • 37
  • 105
  • 183

1 Answers1

6

tr translates one character to another character, it doesn't map to/from strings, and so it can't map a newline to a string. Trying to use sed to do it gets you an unintelligible and/or non-portable mess. Just use awk:

awk -v ORS="'," '1' file

Hang on - your posted example doesn't show you replacing newlines with ', which would be:

$ awk -v ORS="'," '1' file
something',newline',newline again',$

it shows you appending ', at the end of each line which is a completely different thing. You still can't do that with tr but you could do it with sed or awk:

$ sed 's/$/'\'',/' file
something',
newline',
newline again',

$ awk -v ORS="',\n" '1' file
something',
newline',
newline again',
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • `awk` is okay, but I'd prefer to stick to the tools I know. Is there no possible way to do it using `tr`? – makansij Nov 29 '17 at 15:30
  • No, `tr` is for translating one char to another but you want to convert one char to a multi-char string. You're going to have an extremely difficult time writing software if you stick to the tools you know, whether they're the right tool for the job or not, rather than learning the tools appropriate to each job. You're trading off a brief learning curve for a lifetime of time-consuming, inefficient, buggy coding. – Ed Morton Nov 29 '17 at 15:37
  • What is the meaning of the `'1'`? – Jas Jan 08 '20 at 10:19
  • It's a constant true condition and so invokes awks default action of printing the current record. An extremely common awk idiom. – Ed Morton Jan 08 '20 at 14:20