3

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?

2

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 '17 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 '17 at 3:00
  • @speld_rwong Updated – George Vasiliou May 1 '17 at 11:01
1
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.
0

This is the sed command you are looking for:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.