10

I want to use the output of find command with one of my scripts, in one command.

My script accepts:

some-script --input file1.txt file2.txt file3.txt --output final.txt

I want to replace file1.txt file2.txt file3.txt with a `find command.

some-script --input `find ./txts/*/*.txt` --output final.txt

But this breaks, as there are new lines in the output of find command.

1
  • 1
    Try using -print0 argument find, that will print the result without the newline Commented Jan 18, 2018 at 15:59

3 Answers 3

12

Find can output a space-separated list of results without relying on other commands:

find . -name someFile -type f -printf "%p "

The above will find all files named "someFile" in the current directory or any sub-directories, and then print the results without line breaks.

For example, given this directory tree:

.../dir1/someFile.txt
.../dir1/dir2/someFile.txt

Running find . -name '*.txt' -type f -printf "%p " from dir1 will output:

someFile.txt ./dir2/someFile.txt

The arguments, options, and "actions" (i.e. -printf) passed to the above find command can be modified as follows:

  • If you don't give the -type f option, find will report file system entries of all types named someFile. Further, find's man page lists other parameters that can be given to -type that will cause find to search for directories only, or executable files only, or links only, etc...
  • Change -printf "%p " to -printf "%f " to print file names sans path, or again, see find's man page for other format specifications that find's printf action accepts.
  • Change . to some other directory path to search other directory trees.
Sign up to request clarification or add additional context in comments.

Comments

2

This should be adaptable to whatever shell script language you are using..

Example:

find . -type f | grep "\.cc" > ~/lolz.tmp
tr '\n' ' ' < ~/lolz.tmp

Your example:

find ./txts/*/*.txt > ~/lolz2.tmp
tr '\n' ' ' < ~/lolz2.tmp

3 Comments

Why use an extra temp file when you can just pipe ??
Of course you can pipe as well, all these tools support that
How about tr -d '\n'?
0

Why dont you use the ls command instead of find command. e.g. some-script --input ls ./txts/*/*.txt --output final.txt ls output the files as ./txt/file1.txt ./txt/one/file2.txt .. etc

EDIT --- You could use the find and replace the newline with space as follows :
some-script --input find ./txts/*/*.txt | tr '\n' ' ' --output final.txt

1 Comment

Don't know if ls will be supported elsewhere, also doesn't give exactly one space

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.