4

I have a list of folders and inside every folder I have the file " file.txt" which has the same name in all the folders. I wanted to collect the path for this file from all the folders and save it in a text file. In order to do so, I ran the following command in the parent folder :

find $PWD -type f -name "file.txt" > paths.txt

This command stored all the paths to this file from all the folders, in the file"path.txt " as follow:

a/b/c/1/file.txt
a/b/c/2/file.txt
a/b/c/3/file.txt
a/b/c/4/file.txt
a/b/c/5/file.txt
a/b/c/6/file.txt
a/b/c/7/file.txt
.
.
.
.

How can I create space between the lines in the file "path.txt" so it can show as follow:

/a/b/c/1/file.txt /a/b/c/2/file.txt /a/b/c/3/file.txt /a/b/c/4/file.txt /a/b/c/5/file.txt /a/b/c/6/file.txt /a/b/c/7/file.txt ...
3

You can also take advantage of the fact that the shell strips newlines from command substitutions. So, instead of find $PWD -type f -name "file.txt" > paths.txt, you can do (note that you don't need the $PWD, it is the default value for find):

echo $(find $PWD -type f -name "file.txt") > paths.txt

or

printf '%s ' $(find $PWD -type f -name "file.txt") > paths.txt
7

One more way, assuming GNU find(1), just for fun:

find $PWD -type f -name "file.txt" -printf '%p '
  • 1
    +1. You can add a final newline to your output like this: find "$PWD" -type f -name "file.txt" -printf '%p '; printf '\n' – Dennis Williamson Jun 24 '16 at 20:59
5

You can replace the LF character with a space using the 'tr' command

tr '\012' ' ' < path.txt

This can be part of the original command:

find $PWD -type f -name "file.txt" | tr '\012' ' ' > paths.txt
  • @goro, if one of these answers solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon Jun 24 '16 at 17:59
4

One simple way would be to pipe the find output through xargs (whose default action when no explicit command is given is to echo its arguments)

find $PWD -type f -name "file.txt" | xargs > paths.txt

Unlike simply replacing all the newlines with spaces, this preserves the final newline.

3

You can use, paste too,

find . -type f -name "path.txt" -exec paste -d' ' -s {} \; > path.txt
  • This works on the contents of the files, not the filenames. Did you mean find . -type f -name "*.tex" | paste -d' ' -s -? – muru Jun 25 '16 at 11:33
  • @muru it does work, in this case it does. I tested out before posting here. Even you can also test that. – Rahul Jun 25 '16 at 14:19

Your Answer

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