LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Out of ls into array (https://www.linuxquestions.org/questions/linux-newbie-8/out-of-ls-into-array-4175413026/)

eamoss 06-23-2012 02:55 PM

Out of ls into array
 
I am trying to put the output of an ls into a variable which I am able to do with the below command.
Code:

TEST=$(ls)
which will give me
Code:

file1.txt file2.txt file3.txt f1.txt f2.txt a.z b.z c.x
but I only want the files that start with file or f so I changed it to
Code:

TEST=$(ls file* -o f*)
but now I am getting unwanted information like
Code:

drwxr--r--  1 fred  editors  4096  file1 -rw-r--r--  1 fred  editors  30405  file2 -r-xr-xr-x  1 fred  fred      8460  f1
How do I just get the file names and put them into array?

suicidaleggroll 06-23-2012 03:00 PM

The -o flag is what's causing the problem, that switches output to a long listing, which is why you're seeing permissions, owner, etc.

Just remove the -o, and also any file that begins with "file" will also begin with "f", so you only need to search on files that begin with "f" in order to grab both.

Code:

TEST=$(ls f*)
Also, it's generally common practice to reserve all caps for environment variables. Local variables in a script should generally be lower case or mixed upper/lower case so as to prevent confusion.

eamoss 06-23-2012 03:24 PM

I should have used better examples but the two files I want are not the same format lets say file1.txt and doc1.f instead of f1 I want to search for. How do I do this?

Also how would I sort the output based on the number at the end of the file?

unSpawn 06-23-2012 04:28 PM

See Why you shouldn't parse the output of ls(1) and while you're there anyway also see http://mywiki.wooledge.org/BashFAQ and http://mywiki.wooledge.org/BashPitfalls.

David the H. 06-24-2012 10:56 AM

The OP example also sets the values to a single scalar variable. Array syntax is "array=( <wordlist> )"

Notice too that the globbing patterns in the OP example are expanded and passed to ls before it's executed, so you're really just using it as a superfluous "print" command (and which would be subject to wordsplitting if used inside array brackets).

You can simply use the globs directly to set the array instead:

Code:

filearr=( file* doc* )

for f in "${filearr[@]}"; do

        echo "This is file: $f"

done

Finally, since environment variables are generally all upper-case, it's good practice to keep your own user variables in lower-case or mixed-case to help differentiate them.


All times are GMT -5. The time now is 10:20 PM.