简体   繁体   中英

Absolute path to file as a variable in bash

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 directory and similarly in every line where these commands occur. What did I do wrong?

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, eg 42 31314 . To prevent this, you should match a non-digit at the beginning:

grep -o -E '(^|[^0-9])31415925'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM