1

I tried to look for this but couldn't find anything that would suit me. My problem is that i need to convert content of multiple files that have the extension .txt to one line, for example:

1
2
3
4

I would like to convert to 1234 or 1 2 3 4.

I also have subfolders that I would like to be included. I tried multiple attempts with Linux, and even tried TextCrawler 3 for Windows, but nothing really helped me.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • Possible duplicate of [Transpose a file in bash](http://stackoverflow.com/questions/1729824/transpose-a-file-in-bash) – PoX Jan 24 '16 at 02:57

3 Answers3

1

Try translate:

cat *.txt | tr -d '\n'

-d means to delete all newline \n characters.

If you want to have the space, you can do

cat *.txt | tr '\n' ' '
pfnuesel
  • 14,093
  • 14
  • 58
  • 71
1

To remove newlines or replace them with spaces:

$ paste -s -d '' infile
1234
$ paste -s -d ' ' infile
1 2 3 4

This only prints to stdout. To change the file in place:

$ paste -s -d ' ' infile > infile.tmp && mv infile.tmp infile
$ cat infile
1 2 3 4

To do this for many files, for example all .txt files in the current folder and all subfolders:

$ find -name '*.txt' -exec bash -c 'paste -s -d " " {} > {}.tmp && mv {}.tmp {}' \;

This is not very elegant as it creates a subshell in the exec part, but when there is redirection in the exec part of find, that's a way to do it.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
0

Remove all line breaks from the files in *.txt

sed -z -i 's/\n//g' *.txt

Convert all line breaks to spaces in *.txt

sed -z -i 's/\n/ /g' *.txt

but for subdirectories you need some help from find.

find -name "*.txt" -exec sed -z -i 's/\n/ /g' {} ';'
Jasen
  • 11,837
  • 2
  • 30
  • 48