Reputation: 31
FOLDERS=$( basename "$(find "${LOG_DIR}" ! -path "${LOG_DIR}" -type d )")
/storage/archive/fakeagent/2018-07-12
/storage/archive/fakeagent/2018-06-22
With the find
command I get this list of folders, and I would like to get the last foldername (dates). When I use basename
, I only get back one folder name, the last one: 2018-08-16
.
How should I get all of the foldernames?
2018-07-12
2018-07-14
...
2018-08-16
Upvotes: 2
Views: 81
Reputation: 7337
You should not use the command like this in my opinion. You are mixing folders from different locations into one list, it's largely pointless. In other words, retain the full path in your results if it is going to be of any value. Another thing, you may want to put the values in an array so I will provide an alternative to the answers above :
array=()
while IFS= read -r -d $'\0'; do
array+=("$(echo $REPLY | sed 's:.*/::')")
done < <(find . -type d -print0)
echo ${array[@]}
Upvotes: 0
Reputation: 52431
You could use awk to print whatever is after the last slash of each line:
find "${LOG_DIR}" ! -path "${LOG_DIR}" -type d | awk -F'/' '{print $NF}'
Or you can tell find
to print just the basename directly:
find "${LOG_DIR}" ! -path "${LOG_DIR}" -type d -printf '%f\n'
As a side note, uppercase variable names are discouraged as they're more likely to clash with environment and shell variables, see the POSIX spec here, fourth paragraph.
Upvotes: 4
Reputation: 13259
You need to use option -a
in the basename
command to allow multiple arguments:
basename -a $(find "${LOG_DIR}" ! -path "${LOG_DIR}" -type d )
basename --help
shows:
-a, --multiple support multiple arguments and treat each as a NAME
If some of your folder have spaces (or control character), you'd better use option -exec
in the find
command:
find "$LOG_DIR" -type d -exec basename "{}" \;
Upvotes: 4