I've added the count-the-files example from #1852 since it seems to be another general case; getting a count of files, as opposed to using the actual names.

Matthew O. Persico
2020-03-02 19:48:54 -05:00
parent d346a91116
commit d765242b59

@@ -5,13 +5,19 @@
```sh
ls -l | grep " $USER " | grep '\.txt$'
```
```sh
NUMGZ="$(ls -l *.gz | wc -l)"
```
### Correct code:
```sh
find . -maxdepth 1 -name '*.txt' -user "$USER"
find . -maxdepth 1 -name '*.txt' -user "$USER" # Using the names of the files
```
```sh
gz_files=(*.gz)
numgz=${#gz_files[@]} # Sometimes, you just need a count
````
### Rationale:
`ls` is only intended for human consumption: it has a loose, non-standard format and may "clean up" filenames to make output easier to read.
@@ -32,7 +38,7 @@ It shows three seemingly identical filenames, and did you spot the time format c
#### Just the filenames, ma'am
`ls` can usually be replaced by `find` if it's just the filenames you're after. Note that if you are using `ls` to get at the contents of a directory, a straight substitution of `find` may not yield the same results as `ls`. Here is an example:
`ls` can usually be replaced by `find` if it's just the filenames, or a count of them, that you're after. Note that if you are using `ls` to get at the contents of a directory, a straight substitution of `find` may not yield the same results as `ls`. Here is an example:
```
$ ls -c1 .snapshot