首页 > 解决方案 > Linux下grep与IF合并的问题

问题描述

嗨,我正在尝试将 grep 与 if 一起使用,如果在目录下找到该值,则应使用“_1”更新文件名,否则复制到其他目录

cd /home/inbound/ftp
f3=822220222 #ordernumber which change every time for this instance we use this 

   if [ grep -lq $f3 ]; then
   f4=`find . -name *$f3*` #trying to get the existing file name if available 
   mv "$f4" "$f4_1"        #updating existing file with "_1"
else
   cp $file /home/outbound/ftp  

标签: linuxshell

解决方案


grep 命令可用于在文件或输出中搜索模式。它可以通过管道连接到 ls 以检查这一点。但是,对于您的情况,以下将是查找文件是否存在的更好选择

cd /home/inbound/ftp
f3=822220222 #ordernumber which change every time for this instance we use this 

   if [ -f "*$f3*" ]; then
   f4=`find . -name *$f3*` #trying to get the existing file name if available 
   mv "$f4" "$f4_1"        #updating existing file with "_1"
else
   cp $file /home/outbound/ftp

但是,这会在变量 f3 中检查您的订单号。但是,您已经知道要复制的文件名。所以你可以使用它而不是 f3。

cd /home/inbound/ftp
filename=`basename $file` #file name of the File being FTPed

   if [ -f $filename ]; then
   mv "$filename" "$filename_1"        #updating existing file with "_1"
   fi   # closing this here will make sure the file gets copied all the time
   cp $file /home/outbound/ftp

推荐阅读