首页 > 解决方案 > shell脚本逐行从文本文件中读取文件名并确认它们存在于两个不同的目录中

问题描述

我需要从文本文件中读取文件列表并在 unix 的两个不同目录中搜索这些文件,如果不存在,我需要打印文件名。我编写了以下 shell 脚本

#!usr/bin/ksh
while 
read -r filename ; do
if [ -e $filename ] || [ -e /demo/bin/$filename ];
then
echo "File Found!!!! "
else
echo "not found $filename"
fi
done < "$1"

但问题是,如果我在脚本中硬编码文件名,它会显示“找到文件”。但是如果我执行相同的脚本相同的文件名,则没有对名称进行硬编码,它显示未找到。我已将所有需要搜索的文件名存储在名为 abc.txt 的不同文件中。

我正在执行上面的脚本,如 sh isFileExist.sh abc.txt

标签: bashshellunix

解决方案


我创建了一个测试目录和文件来展示它是如何完成的。

创建目录dir1 anddir2`

mkdir -p dir{1..2}

检查目录。

ls 

dir1  dir2

创建文件。

touch dir{1..2}/{1..10}.txt

检查文件。

ls dir{1..2}/
dir1/:
10.txt  1.txt  2.txt  3.txt  4.txt  5.txt  6.txt  7.txt  8.txt  9.txt

dir2/:
10.txt  1.txt  2.txt  3.txt  4.txt  5.txt  6.txt  7.txt  8.txt  9.txt

创建文件的内容。

printf '%s\n' {1..10}.txt > list_of_files.txt
printf '%s\n' {a..c} >> list_of_files.txt 

检查文件的内容。

cat list_of_files.txt

输出是

1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
10.txt
a
b
c

变量foodir1并且变量bardir2脚本中。

#!/bin/sh

foo=dir1
bar=dir2

while read -r files_in_text; do
  if  [ ! -e "$foo"/"$files_in_text" ] && [ ! -e "$bar"/"$files_in_text" ]; then
    printf 'files %s and %s does not exists!\n' "$foo"/"$files_in_text" "$bar"/"$files_in_text"
  else
    printf 'files %s and %s does exists.\n' "$foo"/"$files_in_text" "$bar"/"$files_in_text"
  fi
done < list_of_files.txt

输出应该是

files dir1/1.txt and dir2/1.txt does exists.
files dir1/2.txt and dir2/2.txt does exists.
files dir1/3.txt and dir2/3.txt does exists.
files dir1/4.txt and dir2/4.txt does exists.
files dir1/5.txt and dir2/5.txt does exists.
files dir1/6.txt and dir2/6.txt does exists.
files dir1/7.txt and dir2/7.txt does exists.
files dir1/8.txt and dir2/8.txt does exists.
files dir1/9.txt and dir2/9.txt does exists.
files dir1/10.txt and dir2/10.txt does exists.
files dir1/a and dir2/a does not exists!
files dir1/b and dir2/b does not exists!
files dir1/c and dir2/c does not exists!

推荐阅读