如何在linux shell脚本中使用正则表达式检查文件名

时间:2014-07-23 05:40:00

标签: regex linux shell

让我知道合适的正则表达式来检查linux shell脚本中的以下文件名。

VMHOST_YYYYMMDD_CPU.csv
VMHOST_YYYYMMDD_MEM.csv
VMHOST_YYYYMMDD_DISK.csv
VMHOST_YYYYMMDD_NET.csv
VMOS_YYYYMMDD_CPU.csv
VMOS_YYYYMMDD_MEM.csv
VMOS_YYYYMMDD_DISK.csv
VMOS_YYYYMMDD_NET.csv

我试过这样:

if [[ $filename == [VMHOST|VMOS][_][0-9]{8}[_][CPU|MEM|DISK|NET][.]csv ]]; then
        echo "$filename"
fi

但它不起作用。 所以有人可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

使用扩展模式匹配:

shopt -s extglob  ## Required if Bash is earlier than 4.1.
[[ $filename == @(VMHOST|VMOS)_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_@(CPU|MEM|DISK|NET).csv ]] || echo "== $filename failed."

或者只是使用正则表达式:

[[ $filename =~ (VMHOST|VMOS)_[0-9]{8}_(CPU|MEM|DISK|NET)[.]csv ]]

如果Bash早于4.0,则需要将其存储在变量中:

re='(VMHOST|VMOS)_[0-9]{8}_(CPU|MEM|DISK|NET)[.]csv'
[[ $filename =~ $re ]]

通过扩展模式匹配,您可以跳过测试并只展开您只需要的文件:

shopt -s extglob
for filename in @(VMHOST|VMOS)_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_@(CPU|MEM|DISK|NET).csv; do
    echo "$filename"
done

测试:

#!/bin/bash

names=(VMHOST_00000000_CPU.csv VMHOST_00000000_MEM.csv VMHOST_00000000_DISK.csv VMHOST_00000000_NET.csv VMOS_00000000_CPU.csv VMOS_00000000_MEM.csv VMOS_00000000_DISK.csv VMOS_00000000_NET.csv)

re='(VMHOST|VMOS)_[0-9]{8}_(CPU|MEM|DISK|NET)[.]csv'
for filename in "${names[@]}"; do
    [[ $filename == @(VMHOST|VMOS)_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_@(CPU|MEM|DISK|NET).csv ]] && echo "$filename (extglob ok)"
    [[ $filename =~ $re ]] && echo "$filename (regex ok)"
    echo
done

输出:

VMHOST_00000000_CPU.csv (extglob ok)
VMHOST_00000000_CPU.csv (regex ok)

VMHOST_00000000_MEM.csv (extglob ok)
VMHOST_00000000_MEM.csv (regex ok)

VMHOST_00000000_DISK.csv (extglob ok)
VMHOST_00000000_DISK.csv (regex ok)

VMHOST_00000000_NET.csv (extglob ok)
VMHOST_00000000_NET.csv (regex ok)

VMOS_00000000_CPU.csv (extglob ok)
VMOS_00000000_CPU.csv (regex ok)

VMOS_00000000_MEM.csv (extglob ok)
VMOS_00000000_MEM.csv (regex ok)

VMOS_00000000_DISK.csv (extglob ok)
VMOS_00000000_DISK.csv (regex ok)

VMOS_00000000_NET.csv (extglob ok)
VMOS_00000000_NET.csv (regex ok)

答案 1 :(得分:1)

使用它:

if [[ $f =~ (VMHOST|VMOS)_[0-9]{8}_(CPU|MEM|DISK|NET)\.csv ]]
  then
    echo $f
fi

请参阅demo