Iterate over each line of output ls -l

I want to iterate over each line in the output of ls -l / some / dir / * Right now I'm trying: for x in $(ls -l $1); do echo $x done for x in $(ls -l $1); do echo $x done , however this is repeated for each element in the line separately, so I get

-r - r -----
one
ivanevf
eng
1074
Apr
22
13:07
File1

-r - r -----
one
ivanevf
eng
1074
Apr
22
13:17
File2

I want to iterate over each row as a whole.

How to do it?

Thank.

+75
linux shell
May 18 '10 at 18:24
source share
7 answers

Set IFS for a new line, for example:

 IFS=' ' for x in `ls -l $1`; do echo $x; done 

Put a wrapper around it if you don't want to constantly install IFS:

 (IFS=' ' for x in `ls -l $1`; do echo $x; done) 

Or use while | read instead:

 ls -l $1 | while read x; do echo $x; done 

Another option that runs while / read at the same shell level:

 while read x; do echo $x; done << EOF $(ls -l $1) EOF 
+168
May 18 '10 at 18:50
source share
β€” -
 #!/bin/bash for x in "$(ls -l $1)"; do echo "$x" done 
+10
May 18 '10 at 18:37
source share

It depends on what you want to do with each line. awk is a useful utility for this type of processing. Example:

  ls -l | awk '{print $9, $5}' 

.. on my system prints the name and size of each item in the directory.

+7
May 18 '10 at 18:30
source share

You can also try the find . If you only need the files in the current directory:

find . -d 1 -prune -ls

Run a command for each of them?

find . -d 1 -prune -exec echo {} \;

Count lines, but only in files?

find . -d 1 -prune -type f -exec wc -l {} \;

+4
May 22 '10 at 6:08 a.m.
source share

As already mentioned, awk is the right tool for this. If you do not want to use awk, instead of parsing the output of "ls -l" in turn, you can iterate over all the files and do "ls -l" for each individual file, for example:

 for x in * ; do echo `ls -ld $x` ; done 
+3
May 18 '10 at 18:46
source share

The read (1) utility, along with reconfiguring the output of the ls (1) command, will do what you want.

+2
May 18 '10 at 18:39
source share

So, why didn’t anyone suggest just using options that eliminate those parts that he doesn’t want to process.

In modern Debian, you just get your file:

 ls --format=single-column 

In addition, you do not need to pay attention to the directory in which you use it if you use the full directory:

 ls --format=single-column /root/dir/starting/point/to/target/dir/ 

This last command I use above, and I get the following output:

 bot@dev:~/downloaded/Daily# ls --format=single-column /home/bot/downloaded/Daily/*.gz /home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141119_IENT1.txt.gz /home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141120_IENT1.txt.gz /home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141121_IENT1.txt.gz 
0
Dec 21 '14 at 20:45
source share



All Articles