Linux 巴什:艾利夫不工作了
我将编写一个bash脚本,它返回指定作业的PDF文件列表中的标题和文档类型以及其他一些内容。所以我试图编写一个函数来获取文档类型。当文档类型为ACM或MIT时,它工作正常,但当输出在elif块中时,它显示“未找到命令”。我的密码在这里-Linux 巴什:艾利夫不工作了,linux,bash,shell,Linux,Bash,Shell,我将编写一个bash脚本,它返回指定作业的PDF文件列表中的标题和文档类型以及其他一些内容。所以我试图编写一个函数来获取文档类型。当文档类型为ACM或MIT时,它工作正常,但当输出在elif块中时,它显示“未找到命令”。我的密码在这里- #!/bin/bash function get_type(){ if less "$1" | grep -q -i "ACM TRANSACTIONS" then type="ACM Transactions" elif less "$1" | grep
#!/bin/bash
function get_type(){
if less "$1" | grep -q -i "ACM TRANSACTIONS"
then
type="ACM Transactions"
elif less "$1" | grep -q -i "journal homepage: www.elsevier.com"
then
type= "ELSEVIER"
elif less "$1" | grep -q -i "IEEE TRANSACTIONS"
then
type= "IEEE Transactions"
else
type="MIT Press"
fi
echo $type
}
for file in ~/Desktop/1105063/papers/*;
do
get_type "$file"
done
这是输出-
shawon@Shawon-Linux:~/Desktop/1105063$ ./test.sh
./test.sh: line 12: IEEE Transactions: command not found
[...]
请注意,在shell中,空格通常用于分隔shell术语中的单词。
=
符号周围的变量赋值中不得有空格。使用
type="IEEE Transactions"
因为
type= "IEEE Transactions"
是对
类型
的一次赋值,使用空字符串,然后尝试执行IEEE事务
命令(该命令显然不存在)。在赋值之前删除空格
type= "ELSEVIER"
此外,最好将命令放在括号内:
if ( less "$1" | grep -q -i "ACM TRANSACTIONS" )
建议:
#!/bin/bash
function get_type(){
if grep -q -i "ACM TRANSACTIONS" "$1"; then
type="ACM Transactions"
elif grep -q -i "journal homepage: www.elsevier.com" "$1"; then
type="ELSEVIER"
elif grep -q -i "IEEE TRANSACTIONS" "$1"; then
type="IEEE Transactions"
else
type="MIT Press"
fi
echo "$type"
}
for file in ~/Desktop/1105063/papers/*; do
get_type "$file"
done
使用开关构造可以避免elif。 不是很好的
case
示例,您需要将var转换为小写,并用反斜杠转义所有空格
#!/bin/bash
function gettype {
# echo "Debug: Input $1"
typeset -l x
x=$1
# echo "Debug: x=$x"
case "$x" in
*acm\ transactions*) echo "ACM Transactions" ;;
*journal\ homepage:\ www.elsevier.com*) echo "ELSEVIER" ;;
*ieee\ transactions*) echo "IEEE Transactions" ;;
*) echo "MIT Press" ;;
esac
}
# Some test-calls
gettype "String with acm transActions"
gettype "String without transActions written complete"
gettype "String with the journal homepage: WWW.ELSEVIER.COM in uppercase."
编辑:
此gettype()与OP的gettype()不同。My gettype()解析字符串,OP将搜索文件名为$1的文件。
当您想使用my gettype()时,首先必须从pdf中提取正确的字符串(可能类似)。这里不需要
less
:grep-qi“SEARCH string”“$1”
就足够了。请看一看:谢谢!我现在正在为这样愚蠢的错误自责。@user3027677-Heh。发生在我们当中最好的人身上:-)谢谢!我会试试这个。我正在阅读pdf文件,所以如果没有更少的文件,它就无法工作。谢谢你的帮助。也许你可以用strings
[…或者尝试将选项-z
添加到所有三个grep
s中。括号是可怕的做法;它们无缘无故地导致子shell。我不知道子shell…真的吗?是的!你应该这样做!更好的是:D bash语言是一种非常强大的语言。你可能可以用128种不同的方式做同样的事情。