linux - 文件的绝对路径作为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
同样出现在这些命令出现的每一行中。我做错了什么?
解决方案
像这样的行:
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'
推荐阅读
- r - 计算R中各组的平均值
- android - 如何将 JSON 解析为 viewpager
- php - 下载失败。cURL 错误 60:SSL 证书问题:证书已过期
- python - 字符串 ConfigObj 中的 Configspec
- jquery - 如何解决 jquery-validate + bootstrap has-error 冲突
- excel - 提取 Outlook 邮件文件夹的第一个表
- python - pip - 无法安装 Fastai
- javascript - Algolia 使用 Javascript 显示数组值
- mysql - 为什么 Spring Boot 应用程序不会从 Postgresql 中的实体生成表?
- html - 使不同列中的文本以相同的方式转到新行