首页 > 解决方案 > 文件的绝对路径作为bash中的变量

问题描述

我编写了一个程序,该程序应该搜索一长串随机数字以找到 pi 的最长十进制描述(但不超过 9)。代码是:

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

等等

我的错误信息wc: 0] No such file or directory ./pierex.sh: line 7: grep: No such file or directory同样出现在这些命令出现的每一行中。我做错了什么?

标签: linuxbash

解决方案


像这样的行:

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

应该:

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

替换命令输出的语法是$(command), not <command>。并且该[命令需要在命令名称和参数之间有一个空格,就像所有其他命令一样。

顺便说一句,您可以在不重复运行的情况下执行此操作grep。您可以使用:

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

这将返回最长的匹配,然后你可以得到$match. 这假设文件中只有一个匹配项;如果没有,您可以按长度对结果进行排序并获得最长的结果。请参阅按行长对文本文件进行排序,包括空格

另请注意,所有这些正则表达式都将匹配另一个数字中间某处的 π 的数字,例如 42 31314。为了防止这种情况,您应该在开头匹配一个非数字:

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

推荐阅读