簡體   English   中英

Bash檢查文件匹配的正則表達式是否存在並將文件名分配給變量

[英]Bash check if file matching regex exists and assign filename to variable

我正在尋找一種快速,簡短和可移植的方法來檢查當前工作目錄中是否存在與正則表達式(env(ironment)?|requirements).ya?ml相匹配的文件,如果是,則將其基名分配給變量$FILE進行進一步處理。

基本上,我想結合使用手柄

for FILE in environment.yml env.yml requirements.yml environment.yaml env.yaml requirements.yaml; do
  if [ -e $FILE ]; then
    ...
  fi
done

使用正則表達式

if test -n "$(find -E . -maxdepth 1 -regex '.*(env(ironment)?|requirements).ya?ml' -print -quit)"
then
  ...
fi

將其粘貼到變量中:

file="$(find -E . -maxdepth 1 -regex '.*(env(ironment)?|requirements).ya?ml' -print -quit)"

if [ -n "$file" ]
then
  echo "I found $file"
else
  echo "No such file."
fi

另外,您可以保持循環並使用大括號擴展來縮短循環:

for file in {env{,ironment},requirements}.{yml,yaml} 
do
  if [ -e "$file" ]
  then
    echo "Found $file"
  else
    echo "There is no $file"
  fi
done

或直接使用bash的extglob匹配文件:

shopt -s nullglob
for file in @(env?(ironment)|requirements).y?(a)ml
do
  echo "Found $file"
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM