我正在创建一个脚本来帮助我完成日常工作并实现自动化。我尝试在while循环中输入多行时遇到了问题。我通常在for循环中执行它,但是我通过命令执行它。
示例:
for i in `cat listoffiles.txt`
do
echo $i
find <path> -name *$i* | awk -F "." {'print $4'} #to display a specific value
done
现在我尝试使用while循环自动化它。在读取多个输入行时遇到问题。
例如:
我想搜索这些输入:
有关 例 仅
这是我的脚本:
#!/bin/ksh
echo Please enter file #:
read Var1
while true
do
VarSession=`find $OT_DIR/archive*/ -name *$Var1* | awk -F "." {'print $4'}`
if [ "$VarSession" = "" ]
then
echo No match for File# $Var1 on this leg or is out of retention.
else
echo File# $Var1 is under Session# $VarSession
fi
done
答案 0 :(得分:1)
VarSession=`find $OT_DIR/archive*/ -name *$Var1* | awk -F "." {'print $4'}`
假设您提供1 2 3
作为输入,上面的行转换为此
VarSession=`find $OT_DIR/archive*/ -name "1 2 3" | awk -F "." {'print $4'}`
但是你想分别搜索所有这些值,所以你需要另一个循环。如果遍历以空格分隔的条目,for
循环将起作用。
此外,根据您显示的原始脚本,我假设您希望脚本按文件搜索,而不是扫描整个目录。但是,上面的语句会将所有输出放在变量中,而不会遍历它。要逐行遍历,while
循环可以完成工作。
#!/bin/ksh
# -n switch suppresses printing a newline
echo -n 'Please enter file #: '
read Var1
# Traverse over all entered values in Var1 (separated by white space)
for i in $Var1
do
#Set a flag to zero, logic explained later
Flag=0
find $OT_DIR/archive*/ -name *$i* | while read FileName
do
#Set the Flag to 1 if find command finds something
Flag=1
VarSession=`echo $FileName | awk -F "." {'print $4'}`
if [ "$VarSession" = "" ]
then
#If find found a file but VarSession has nothing then file name is not correct
echo "Some conventions went wrong in file name: $FileName"
else
echo "File# $Var1 is under Session# $VarSession"
fi
done
#If find found nothing, there was no match
if [ $Flag -eq 0 ]
then
echo No match for File# $Var1 on this leg or is out of retention.
fi
done