I use the command:

tr '\n' ' ' < input.txt > output.txt

to convert new lines to spaces using tr command.

It works fine for single files - but I have multiple files I need to run a single command on... similar to the following command for doing text swapping:

find /directory/. -type f -exec sed -i 's/oldtext/newtext/g' {} \;

Is there a command I can add to a bash script (like the one above using find) to remove \n?

4 Answers 4


This will work even without any loop for all filenames starting with file:

perl -pe 's/\n/ /g' file*

For such operations, i prefer perl. Has the same syntax with sed , is portable and don't have all those strange sed parameters. You can also apply -i switch to perl (like sed) to make in-place changes: perl -i.old -pe .... (old file will be backed up with extension .old -You can just use -i and no backup file will be kept)

If you prefer you can use your find command like this:

$ find . -type f -name 'file*' -exec bash -c 'tr "\n" " " <$0 >$0.new' {} \;
  • The /g modifier is redundant as there can be only one newline in a line.
    – user218374
    May 1, 2017 at 2:58
  • You need to redirect the output coming from tr back into the input filename for as it stands now, it's all flowing to the terminal.
    – user218374
    May 1, 2017 at 3:00
  • @speld_rwong Updated May 1, 2017 at 11:01

you could simply loop through the files you're looking to run the command on.

for file in ~/Desktop/*.txt
tr '\n' ' ' < "$file" > "$file"_output.txt
  • You don't have to put semicolons on every line break. You'll need it only when you want to execute multiple commands in a single line.
    – annahri
    Jul 20, 2021 at 7:05
  • Thanks @annahri
    – BMac
    Jul 29, 2021 at 14:19
perl -i -lpe '$\=$"' file.data

  • -i turns ON in-place editing.
  • -l sets ORS = RS = "\n"
  • -p sets up an implicit input file read in + automatic print of records.
  • $\ is the ORS which is set to $" = OFS = space by default.
  • Of course you can give multiple filenames to the perl command.

This is the sed command you are looking for:

find /directory/. -type f -exec sed -i ':begin;$!N;s/\n/ /;tbegin' {} \;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .