0

Here is my sample file

cat test.txt
"IND WEB",
"Speed Web (Internal webserver)",
"Web Bill",

I tried the below two solutions to convert multiline to single line however the double quotes " are lost !!

cat listofapps.txt | xargs -s 8192
IND WEB, Speed Web (Internal webserver), Web Bill,

tr '\n' < listofapps.txt
IND WEB, Speed Web (Internal webserver), Web Bill,

Can you please suggest so that the double quotes remain ?

Ashar
  • 449
  • 3
  • 10
  • 26
  • 1
    Please check that the information in your question accurately reflects what you tried (`tr '\n' < listofapps.txt` isn't a valid command for example - did you mean `tr -d '\n' < listofapps.txt` ?) – steeldriver Feb 22 '21 at 15:06
  • ... and for the `xargs` because quotes are special to `xargs` [Why does xargs strip quotes from input?](https://unix.stackexchange.com/questions/38148/why-does-xargs-strip-quotes-from-input) – αғsнιη Feb 22 '21 at 15:11
  • @steeldriver `tr -d '\n' < listofapps.txt` works !! thank you. I was missing the `-d` – Ashar Feb 22 '21 at 15:11

2 Answers2

2

When you use xargs, the double quotes are lost because they are being interpreted by the xargs utility (see Why does xargs strip quotes from input?).

Your tr command is broken and ought to have given you an error message.

To delete newlines with tr, use

tr -d '\n' <file

To replace the newlines with spaces, use

tr '\n' ' ' <file

To join the lines with spaces:

paste -sd ' ' file

(same as above, except that it adds a newline in the end to make it one valid line of text).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
0

sed way:

sed '${G;s/\n//g;p;};H;d' sample.txt

The same, but with explanation in comment:

sed '
    ${
        # If we are in the last line

        G; # Get anything stored in the hold space

        s/\n//g; # Replace any occurrence of space with nothing

        p; # Print 
    }
   
    # We are not in the last line so 
    H; # save the current line
    d; # and start the next cycle without print
' sample.txt
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
DanieleGrassini
  • 2,769
  • 5
  • 17
  • @Kusalananda, (re: your edit). That still doesn't make it portable as there's nothing allowed after `}` in standard `sed` syntax. It would have to be `sed -e '${G;s/\n//g;p;}' -e 'H;d'` but even then as the whole file ends up in the pattern space, POSIX doesn't give you any warrantee for anything but short files. `sed` is not the best tool for the task here. – Stéphane Chazelas Mar 07 '21 at 16:28
  • @StéphaneChazelas You are correct, but at least my native OpenBSD `sed` can grok it with no errors. So it's _better_ now. The fact that the code reads the whole file into memory is an issue that is part of the original answer. – Kusalananda Mar 07 '21 at 18:00
  • @YetAnotherUser It's a sample, put together for the question. – Kusalananda Mar 08 '21 at 09:23