0

So I'm trying to make a sh script where I put a value that I get from a command, into a variable, in this case n, but I have no idea what I'm doing, and this here obviously doesn't work lol:

  1 n=0
  2 cat test | grep -cE '[0-9]{1,4}' > $n
  3 echo "there were $n lines in test" > rtest1

It makes a rtest1 file which says "there were 0 lines in test"

Test is a file that has 10 lines, by the way.

So how does one assign a value from stdout to a variable in shell scripting? :D

iamAguest
  • 483

1 Answers1

0

What you want is called command substitution:

file=./path/to/some/file
n="$(grep -cE '[0-9]{1,4}' < "$file")"
echo "there were $n matching lines in $file"

Of course you don't need the quotes in the assignment, just n=$(...) would do. But in general you want the quotes around the command substitution. Also note that it eats trailing newlines.

See also:

ilkkachu
  • 138,973
  • When I replace "$file" with "$test" (the name of my file which is in the same directory as the script) and run the script, I get: Error on line1: no such file or directory – iamAguest Aug 09 '18 at 09:11
  • @iamAguest You need to assign the right name in the first line: file=./test – nohillside Aug 09 '18 at 20:09