Shell Bash检查文件名是否包含字符串

时间:2017-01-06 13:30:43

标签: bash shell

我在创建if语句时遇到问题,无法检查目录中的文件是否存在名称中的某个字符串。

例如,我在某个目录中有以下文件:

file_1_ok.txt
file_2_ok.txt
file_3_ok.txt
file_4_ok.txt
other_file_1_ok.py
other_file_2_ok.py
other_file_3_ok.py
other_file_4_ok.py
another_file_1_not_ok.sh
another_file_2_not_ok.sh
another_file_3_not_ok.sh
another_file_4_not_ok.sh

我想将包含1_ok的所有文件复制到另一个目录:

#!/bin/bash
directory1=/FILES/user/directory1/
directory2=/FILES/user/directory2/


string="1_ok"
cd $directory

for every file in $directory1
do
    if [$string = $file]; then
        cp $file $directory2
    fi
done

更新:

Faibbus提出了更简单的答案,但如果您要移除或只是移动不具备您想要的特定字符串的文件,请参阅Inian

其他答案也有效。

4 个答案:

答案 0 :(得分:7)

cp directory1/*1_ok* directory2/

答案 1 :(得分:4)

使用find

find directory1 -maxdepth 1 -name '*1_ok*' -exec cp -v {} directory2 \;

使用find优于glob solution posted by Faibbus的优势在于它可以处理包含1_ok的无限数量的文件,其中glob解决方案将导致argument list too long使用太多参数调用cp时出错。

结论:对于使用有限数量的输入文件进行交互式使用,对于shell脚本来说,glob会很好,我必须使用find

答案 2 :(得分:2)

我建议您使用脚本:

#!/bin/bash

source="/FILES/user/directory1"
target="/FILES/user/directory2"

regex="1_ok"

for file in "$source"/*; do
  if [[ $file =~ $regex ]]; then
    cp -v "$file" "$target"
  fi
done

来自help [[

  

使用=~运算符时,运算符右侧的字符串       匹配为正则表达式。

请看一下:http://www.shellcheck.net/

答案 3 :(得分:1)

extglob中使用以下模式进行bash匹配,

  

+(模式列表)   匹配给定模式的一个或多个实例。

首先按

启用extglob
shopt -s extglob
cp -v directory1/+(*not_ok*)  directory2/

一个例子,

$ ls *.sh
another_file_1_not_ok.sh    another_file_3_not_ok.sh
another_file_2_not_ok.sh    another_file_4_nnoot_ok.sh

$ shopt -s extglob
$ cp -v +(*not_ok*) somedir/
another_file_1_not_ok.sh -> somelib/another_file_1_not_ok.sh
another_file_2_not_ok.sh -> somelib/another_file_2_not_ok.sh
another_file_3_not_ok.sh -> somelib/another_file_3_not_ok.sh

要删除包含此模式的文件以外的文件,请执行

$ rm -v !(*not_ok*) 2>/dev/null