How to find basename of path via pipe

Viewed 10538

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.

3 Answers

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

Since mindepth and maxdepth are GNU extensions, using another one such as printf will not make it less portable.

find "$all_locks" -mindepth 1 -maxdepth 1 -type d -printf '%f\n'

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.

Related