-1

How can I use ls *.txt | wc as a separate variable so I can use it in a loop afterwards? That is

count.files=$(ls *.txt | wc)
...

if count.files -ne 2000; then
echo "message"
fi

I have tried it but it seems it doesn't work.

4
  • count_files=$(ls *.txt | wc -l);if [ ${count_files} -ne 2000 ]; then echo "message";fi
    – Costas
    Mar 5, 2015 at 11:17
  • You have syntax problems. Missing $ in variable substitution and missing [] brackets for -ne to make sense.
    – orion
    Mar 5, 2015 at 12:00
  • It should be noted that all of the answers provided so far do not provide a mechanism for decreasing the count stored in the variable. Unless this if is only a member of a loop that does include some mechanism to decrease the number of files being counted, this will result in an infinite loop.
    – wraeth
    Mar 5, 2015 at 12:00
  • If you are using this counter to iterate over files with a loop, I should point out this possibly the worst way of doing it. Do you need for file in *.txt; do ...; done ?
    – orion
    Mar 5, 2015 at 12:02

3 Answers 3

1

There are several mistakes in you code:

  • in most shells, a variable name cannot contain a dot
  • you need to call wc with the -l flag
  • you need to call ls with the -d flag
  • you need to mark the end of options with -- or use a ./ prefix for ls
  • your if test misses brackets (but maybe that's just stackexchange formatting)
  • that won't work if file names contain newline characters
  • that omits hidden files.

Here is a better working example:

file_count=$(ls -d ./*.txt | wc -l)
if [ $file_count -ne 2000 ]; then echo "message"; fi
1

I think the feature you're thinking of is disciplines. That's a ksh93-only feature:

function count.get {
  .sh.value=$(set -- ~(N)*.txt; echo "$#")
}

Then, whenever $count is expanded, that discipline function is invoked that assigns a value to it.

In zsh, you can also define the content of a variable as code:

count='$(set -- *.txt(N); echo "$#")'

and use it as ${(e)count} for that code to be evaluated upon expansion.

However those give little benefit over the standard way of using a function:

count() (
  set -- [*].txt *.txt
  case $1$2 in
    '[*].txt*.txt') echo 0;;
    *) echo "$#"
  esac
)

(the [*] trick can be avoided with shells that support nullglob options (like ksh93's ~(N) or zsh's (N) above)).

And use it as $(count) (command substitution).

(see the other answers for all the issues with your code).

0

First of all you need to use wc -l to count only newlines. This should work:

#!
filecounter=$(ls *.txt | wc -l)
if [ $filecounter -ne 2000 ]; then echo "message"
fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .