How can I force only relative paths in "find" output?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 How Can I Force Only Relative Paths In &Quot;Find&Quot; Output?
00:45 Accepted Answer Score 14
01:30 Answer 2 Score 39
01:49 Thank you
--
Full question
https://superuser.com/questions/69400/ho...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#linux #commandline #find #tar #recursive
#avk47
ANSWER 1
Score 39
You can use the %P
format in the -printf
directive:
find ${rootDir} -name '*.doc' -printf "%P\n"
will display in your example:
subdir/test.doc
second.doc
You may then use this find
list in a for
expression, in order to run our exec command, as in:
for f in $( find ${rootDir} -name '*.doc' -printf "%P\n" );
do
tar rvf docs.tar ${f}
done
ACCEPTED ANSWER
Score 14
If you run find
from the desired root directory and don't specify an absolute starting point in find
's options, it will output relative paths to the tar
command invocations it constructs. Like so:
cd $rootDir
find . -name '*doc' -exec tar rvf docs.tar {} \;
If you do not want to change the current working directory permanently and are using bash
or similar as your shell you could do
pushd $rootDir
find . -name '*doc' -exec tar rvf docs.tar {} \;
popd
instead.
Note that pushd/popd are not present in all shells, so check the man page as appropriate. They are present in bash but not in the base sh implementation so while explicitly using /bin/bash
you can rely on them you can't if a script asks for /bin/sh
instead (as this may map to a smaller shell that doesn't have bash's enhancements)