Reputation: 15940
I am executing a ls-R /files/
I got the following output
./: nvision
./nvision: layout
./nvision/layout: abcd.txt
I am looking to get path in the listing like
/nvision
/nvision/layout/
/nvision/layout/abcd.txt
and I should be able to copy the required path to a variable
ps: I am not searching for nvision
I am trying to get the list of folders and files under files
folder
can any one help me with that
Upvotes: 1
Views: 2158
Reputation: 19239
Have you tried using find
(see reference)
It would be as easy as find .
to get the list of files and folders inside the current directory. Change the . to any path to obtain the list of files and directories inside that path:
nvision
nvision/abcd.txt
nvision/layout
To save it to a variable
var=`find .`
And to add the initial slash to every line (if required)
var=`find . -exec echo /{} \;`
Here var has no special meaning, it's just the variable name.
To later use the variable you can use $var
or ${var}
. For example, to print it or save it to file:
# Print the variable content
echo $var
# Save the content of var to a file
echo $var > /tmp/file.txt
Upvotes: 4
Reputation: 8587
well the answer is all over this page you should be using find which lists all files found yo can define
where . is current folder otherwise replace . with path you are wishing to search
find .-type d -print
which lists directories only or find
or
find . -type f -print
which will list all files only
if you are looking for both then
find . -print
and if you only wish to define recursive level try
find . -maxdepth 1 -print
and here is a script
#!/bin/bash
for names in $(find . -type f -print); do
echo $names
done
Upvotes: 1
Reputation: 2623
You should really use find for these kind of things. Simply use find directory
. If you require more specific output formatting you can make use of find
's -printf
option. Find is a really powerful tool that also allows all kinds of filtering. Make sure you check the documentation for more information: GNU FindUtils.
To store the results in a variable use one of the following statements:
result=`find ...`
or
result=$(find ...)
You can also use find to directly execute a command for each match using find
's -exec
option. Again, make sure to check out the documentation. It's really comprehensive.
Update (Mac / UNIX users – Linux users are not affected)
BSD find
requires a path. Use
find .
instead of just
find
if you require a listing of all files in your working directory.
Upvotes: 2