How to find basename of path via pipe
Asked Answered
D

3

25

This doesn't work:

find "$all_locks" -mindepth 1 -maxdepth 1 -type d | basename

apparently basename cannot read from stdin - in any case basename requires at least one argument.

Discourtesy answered 9/6, 2019 at 3:50 Comment(3)
Are you simply looking to strip off the final directory name, or are you looking to find the parents of things that might be symbolic links from $all_locks?Hartle
I am just trying to get the basename of each path resulting from findDiscourtesy
So if /path/to/this is a symlink to /some/other/place, should your result be /path/to or /some/other?Hartle
L
32

To apply a command to every result of a piped operation, xargs is your friend. As it says on the man page I linked...

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input.

In this case that means it will take each result from your find command and run basename <find result>ad nauseum, until find has completed its search. I believe what you want is going to look a lot like this:

find "$all_locks" -mindepth 1 -maxdepth 1 -type d | xargs basename

Lashley answered 9/6, 2019 at 4:36 Comment(0)
F
7

The problem here is basename doesn't accept the stdin and hence unnamed pipes may not be useful. I would like to modify your command a little bit. Let me know if it serves the purpose.

find -mindepth 1 -maxdepth 1 -type d -exec basename {}  \;

Note: Not enough reputation to comment, hence posting it here.

Featheredge answered 9/6, 2019 at 4:8 Comment(2)
on ubuntu bash 4, I get find: missing argument to '-exec'...weirdDiscourtesy
@MrCholo, I hope you didn't miss a space between {} and \ ? Because, I can recreate your problem by erasing that space.Featheredge
G
7

With GNU find:

find "$all_locks" -mindepth 1 -maxdepth 1 -type d -printf '%f\n'
Garver answered 9/6, 2019 at 4:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.