0

when I run

find  ~/foo/bar/. -mindepth 1 -maxdepth 1 -type d

I get an output of all subdirectories of the given path. e.g.

/home/user/foo/bar/a
/home/user/foo/bar/b
...
/home/user/foo/bar/abcd

Now I want to use that output as a string so I added -print to replace some of the found results

find  ~/foo/bar/. -mindepth 1 -maxdepth 1 -type d -print | xargs sed 's#/home/user/foo/bar/#some_text"#g'

but the result wasn't as expected

sed: read error on /home/user/foo/bar/./abc: Is a directory

obviously sed doesn't treat the piped arguments as strings my intnended e.g.

some_text/a
some_text/b
...
some_text/abcd
  • 4
    Remove xargs, it's creating arguments from the files. Just piping the output to sed will feed them to sed's standard input. – choroba Jul 30 at 9:26
  • Note that -print is the default, so adding it makes no difference. – choroba Jul 30 at 9:27
  • you are right man I feel stupid – aldr Jul 30 at 9:28
4

Removing the path is better done using find's -printf option:

find ~/foo/bar/ -mindepth 1 -maxdepth 1 -type d -printf 'some_text/%P\n'

%P File's name with the name of the starting-point under which it was found removed.


To fix your sed version, do not use xargs, just pipe directly to sed like @choroba commented alrady.

2

You can pipe the output to find directly to sed (no xarg)
-print is the default action, so it can be ommited
Since you want to remove the path from filename string, you can use the -prinf option from find and format it with -printf '%P\n' (See man 3 printf)

find  ~/foo/bar/. -mindepth 1 -maxdepth 1 -type d | sed 's#/home/user/foo/bar#some_text#g'
# or
find  ~/foo/bar/. -mindepth 1 -maxdepth 1 -type d -printf '%P\n'
1

You could also use awk to replace everyting up to the last / with some_text:

find ~/foo/bar/ -mindepth 1 -maxdepth 1 -type d | awk '{gsub(/^.*\//, "some_text/"); print}'

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.