Linux 尝试创建一个文件以调用另一个文件进行循环搜索
我试图编写一个脚本,调用另一个脚本,并根据输入使用它一次,或在循环中使用它 我编写了一个脚本,只需在文件中搜索一个模式,然后打印文件名并列出搜索结果所在的行。剧本在这里Linux 尝试创建一个文件以调用另一个文件进行循环搜索,linux,bash,shell,scripting,Linux,Bash,Shell,Scripting,我试图编写一个脚本,调用另一个脚本,并根据输入使用它一次,或在循环中使用它 我编写了一个脚本,只需在文件中搜索一个模式,然后打印文件名并列出搜索结果所在的行。剧本在这里 #!/bin/bash if [[ $# < 2 ]] then echo "error: must provide 2 arguments." exit -1 fi if [[ -e $2 ]] then echo "error: second argument must be a file."
#!/bin/bash
if [[ $# < 2 ]]
then
echo "error: must provide 2 arguments."
exit -1
fi
if [[ -e $2 ]]
then
echo "error: second argument must be a file."
exit -2
fi
echo "------ File =" $2 "------"
grep -ne $1 $2
它将只使用脚本,但如果输入为:
./searchscript if testfile
./searchscript if Desktop
它将搜索循环中的所有文件
我的心一如既往地为你们所有人而流。假设你们不想递归搜索:
#!/bin/bash
location=shift
if [[ -d $location ]]
then
for file in $location/*
do
your_script $file
done
else
# Insert a check for whether $location is a real file and exists, if needed
your_script $location
fi
注1:这有一个微妙的错误:如果目录中的某些文件以“.”开头,据我所知,“for*”循环将看不到它们,因此您需要在$location/*$location/*”中添加“
”
注2:如果需要递归搜索,请使用“查找”:
in `find $location`
这个怎么样:
#!/bin/bash
dirSearch() {
for file in $(find $2 -type f)
do
./searchscript $file
done
}
if [ -d $2 ]
then
dirSearch
elif [ -e $2 ]
then
./searchscript $2
fi
或者,如果不想分析find的输出,可以执行以下操作:
#!/bin/bash
if [ -d $2 ]
then
find $2 -type f -exec ./searchscript {} \;
elif [ -e $2 ]
then
./searchscript $2
fi
类似的东西可能会起作用:
#!/bin/bash
do_for_file() {
grep "$1" "$2"
}
do_for_dir() {
cd "$2" || exit 1
for file in *
do
do_for "$1" "$file"
done
cd ..
}
do_for() {
where="file"
[[ -d "$2" ]] && where=dir
do_for_$where "$1" "$2"
}
do_for "$1" "$2"
呃。。。也许太简单了,但是让“grep”做所有的工作怎么样
#myscript
if [ $# -lt 2 ]
then
echo "error: must provide 2 arguments."
exit -1
fi
if [ -e "$2" ]
then
echo "error: second argument must be a file."
exit -2
fi
echo "------ File =" $2 "------"
grep -rne "$1" "$2"
我刚刚在grep调用中添加了“-r”:如果它是一个文件,没有递归,如果它是dir,它将在它上面递归
您甚至可以取消参数检查,让grep吐出相应的错误消息:(保留引号,否则将失败)
那么$1不是模式参数吗?和$2实际的文件/目录?@Looking2Learn-抱歉,没有意识到您想要将模式作为第一个参数传递给外部脚本。如果你这样做了,你是对的,根据需要修改否,不要解析
find
的输出。永远不要解析find
的输出。改用-exec
。该死的,我已经说过十亿次了,而且很可能会永远重复它。:(
。并使用更多的引号。@gniourf\u gniourf您可能已经说过很多次了,但这是我第一次听到它!谢谢您的建议,我会编辑。这个错误出现在顶部的find命令中。我做错了什么?我移动了一些东西。这个脚本似乎没有向第一个脚本传递两个参数[[$$<2]]
完全是错误的。试着用[[10<2]]&&echo“oooooops”
你会有一个惊喜!你可能是说(((#$<2))
或[$+-lt 2]
。出于某种原因,我会使用((#$!=2))
。我只是复制/粘贴了OP的部分并编辑了grep。我应该读那部分的。^^谢谢你的提醒
#myscript
grep -rne "$1" "$2"