Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove new line from find command output

Tags:

shell

terminal

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.

like image 663
KingJulian Avatar asked Jul 25 '14 11:07

KingJulian


2 Answers

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.
like image 60
Loss Mentality Avatar answered Sep 29 '22 05:09

Loss Mentality


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
like image 40
Martin G Avatar answered Sep 29 '22 06:09

Martin G