how to show only filename when cut cmd is not working?

Viewed 164

I m finding all files ending with .sh, but need to show only filenames and without ./

(find -type f \( -name "*[.sh]" \) ) 

it gives me all files ending with .sh and in subdirs too:

./erj.sh
./another/r5.sh
./another/t9.sh
./another/rrr2.sh
./elro/2039jlfsdjf.sh
./elro/tlr.sh
./elro/823.sh
./222.sh
./my_find_sh
./rrr.sh
./4234.sh
./sdf.sh

but using "cut -d. -f1" gives me empty output, because it takes first dot as remove point

find -type f \( -name "*[.sh]" \)  | cut -d. -f1

gives empty line.

3 Answers

Try this:

find -type f \( -name "*.sh" \) -printf "%f\n"

While the alternatives proposed by other users are completely right, in order to get the output you want strictly using the command you posted, you should pick the second field instead of the first one when using cut. Additionally, I don't think the parentheses are needed in that case at all, because it will make no difference.

That said, you can try:

find -type f -name "*.sh" | cut -d\. -f2

Using find and Bash builtin string substitution:

find . -type f -name '*.sh' -printf "%P\n" | while read -r F; do echo ${F%.*}; done

Or with process subsitution for when you need to access variables created within the loop after the loop ends.

while IFS= read -r F; do echo "${F%.*}"; done < <(find . -type f -name '*.sh' -printf "%P\n")

"%P" removes the ./ while ${F%.*} removes the very last extension only. If you want everything after first period gone, ${F%%.*}.

Not clear in your question if you want path removed also, but if so, then wrap up ${F%.*} with a call to basename like so: $(basename "${F%.*}").

Related