bash - 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
解决方案
我创建了一个测试目录和文件来展示它是如何完成的。
创建目录dir1 and
dir2`
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
变量foo
是dir1
并且变量bar
在dir2
脚本中。
#!/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!
推荐阅读
- angular - 如何在Angular 4中删除特定页面的全局styles.css
- copy-paste - 制作按钮(或复选框)并从中复制值以制作值列表
- postgresql - 在 Spring Boot 2 的 postresql 连接上找不到表
- c# - Ef core 不跟踪子集合的更改
- javascript - 如何使用 npm 在 Laravel 中安装 UIkit 3?
- delphi - 使用 firemonkey 连接到已知 BLE 设备的最快方法
- c++ - HDF5 不会在 C++ 中使用 H5Fcreate() 创建文件
- c# - 将 DataGrid 导出到文本文件
- excel - 单元格不为空时的 IF 语句
- dataweave - Dataweave 中的映射