KingJulian
KingJulian

Reputation: 973

Remove new line from find command output

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.

Upvotes: 10

Views: 12058

Answers (3)

Loss Mentality
Loss Mentality

Reputation: 374

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.

Upvotes: 12

Pratham
Pratham

Reputation: 1723

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

Upvotes: 0

Martin G
Martin G

Reputation: 18109

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

Upvotes: 2

Related Questions