Quick Background:
$ ls src file1 file2 dir1 dir2 dir3
Script:
#!/bin/bash for i in src/* ; do if [ -d "$i" ]; then echo "$i" fi done
Output:
src/dir1 src/dir2 src/dir3
However, I want it to read:
dir1 dir2 dir3
Now I realize I could sed/awk the output to remove "src/" however I am curious to know if there is a better way of going about this. Perhaps using a find + while-loop instead.
We use a standard wildcard glob pattern '*' which matches all files. By adding a '/' afterward, we'll match only directories. Then, we assign each directory to the value of a variable dir. In our simple example, we then execute the echo command between do and done to simply output the value of the variable dir.
The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).
Do this instead for the echo
line:
echo $(basename "$i")
No need for forking an external process:
echo "${i##*/}"
It uses the “remove the longest matching prefix” parameter expansion. The */
is the pattern, so it will delete everything from the beginning of the string up to and including the last slash. If there is no slash in the value of $i
, then it is the same as "$i"
.
This particular parameter expansion is specified in POSIX and is part of the legacy of the original Bourne shell. It is supported in all Bourne-like shells (sh, ash, dash, ksh, bash, zsh, etc.). Many of the feature-rich shells (e.g. ksh, bash, and zsh) have other expansions that can handle even more without involving external processes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With