Reputation: 247
folder
|___subfolder
|_____file.txt
|
|___subfolder
|____subfolder
|_______file.txt
etc
I have a folder that looks like this. I want to get all the .txt files but as they all have the same name I also want to add the folder name in front of file.txt.
do
name_folder= $(basename $folder)
echo $name_folder
for subfolder in $folder;
do
find .*txt
done;
done;
I expect $(foldername)basename_txt but this way I am only getting the .txt files
Upvotes: 1
Views: 1118
Reputation: 156
folder=$(echo "${PWD##*/}") #assuming you need only folder name, not full path
# find way from Secespitus
find . -name "*.txt" | while read line
# for each line, using sed adding folder name after last use of character "/"
#then renaming
do mv $(echo $line) $(echo $line | sed "s/\(.*\)\//\1\/$folder/")
done
Upvotes: 2
Reputation: 709
You can use the find
command to get the name with the full path to every .txt file.
find . -name "*.txt"
will print out:
./test/subdir/file.txt
./test/subdir2/subdir/file.txt
If you need the full path you can use that instead of .
in the find
command:
find /home/someone/ -name "*.txt"
will yield:
/home/someone/test/subdir/file.txt
/home/someone/test/subdir2/subdir/file.txt
And if you need only the last directory you can pipe the output of the find
command into sed
:
find /home/someone/ -name "*.txt" | sed 's/.*\/\(.*\/.*txt\)/\1/g'
will yield:
subdir/file.txt
subdir/file.txt
Upvotes: 3