简体   繁体   English

文件的绝对路径作为bash中的变量

[英]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).我写了一个程序,它应该搜索一长串随机数字来找到 pi 的最长十进制描述(但不超过 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.我的错误信息是wc: 0] No such file or directory ./pierex.sh: line 7: grep: No such file or directory并且在出现这些命令的每一行中都类似。 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> .替换命令输出的语法是$(command) ,而不是<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 .顺便说一句,您可以在不重复运行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 .这将返回最长的匹配,然后你就可以得到$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 .还要注意,所有这些正则表达式都将匹配另一个数字中间某处的 π 数字,例如 42 31314 To prevent this, you should match a non-digit at the beginning:为了防止这种情况,您应该在开头匹配一个非数字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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