-3

I wrote a program which is supposed to search through one long string of random digits to find the longest decimal depiction of pi (but no longer than 9). The code is:

read -p 'Please specify one: ' fil1
dire=$( locate $fil1 )
if[ <grep -o '314159265' $dire | wc -w> -gt 0 ]
then
echo The longest decimal representation has 9 digits.
return [0]
fi
if[ <grep -o '31415926' $dire | wc -w> -gt 0 ]
then

etc.

My error message is wc: 0] No such file or directory ./pierex.sh: line 7: grep: No such file or directoryand similarly in every line where these commands occur. What did I do wrong?

Filip Pawelec
  • 53
  • 1
  • 6
  • Put your code in your question, not a _**picture**_ of your code. – Stephen P Oct 22 '18 at 22:39
  • You need spaces around `[` in `if` statements. And you shouldn't have `<` and `>` around `grep ... | wc -2`, you should have `$(` and `)`. – Barmar Oct 23 '18 at 00:08

1 Answers1

3

Lines like:

if [<grep -o '31415925' $dir3 | wc -c> -gt 0]

should be:

if [ $(grep -o '31415925' $dir3 | wc -c) -gt 0 ]

The syntax for substituting the output of a command is $(command), not <command>. And the [ command requires a space between the command name and arguments, just like every other command.

BTW, you can do this without repeatedly running grep. You can use:

match=$(grep -o -E '3(1(4(1(5(9(26?)?)?)?)?)?)?' "$dire")

This will return the longest match, then you can just get the length of $match. THis assumes that there's only one match in the file; if not, you can sort the results by length and get the longest one. See Sort a text file by line length including spaces

Note also that all these regular expressions will match the digits for π somewhere in the middle of another number, e.g. 4231314. To prevent this, you should match a non-digit at the beginning:

grep -o -E '(^|[^0-9])31415925'
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You might warn that your oneliner only works because the decimals don't have a 3. The same approach for finding `31315` will fail: `echo 3131315 | grep -o -E '3(1(3(1(5?)?)?)?)?'` – Walter A Oct 23 '18 at 08:28
  • Thanks a lot, that helped! – Filip Pawelec Oct 23 '18 at 08:39
  • 1
    @WalterA The original method also has that problem. The solution is to match a non-digit at the beginning. I've added that to the answer. – Barmar Oct 23 '18 at 14:07