簡體   English   中英

使用 bash 腳本替換文件名中的多個下划線

[英]Replace multiple underscores in filename using bash script

這里這里做一些閱讀,我發現這個解決方案使用 bash 將文件名中的兩個下划線替換為一個:

for file in *; do
  f=${file//__/_}
  echo $f
done;

但是,我如何最輕松地擴展此表達式以僅用一個替換任意數量的下划線?

通常,將原始代碼放入循環中會比執行其他任何操作更快。

for file in *; do
  f=$file
  while [[ $f = *__* ]]; do
    f=${f//__/_}
  done
  echo "$f"
done

更好的是,如果您使用的是現代 shell 版本,您可以啟用擴展 glob,它提供了類似正則表達式的功能:

shopt -s extglob
for file in *; do
  f=${file//+(_)/_}
  echo "$f"
done

您可以使用sed使用簡單的正則表達式

for file in *; do
  f=$(echo $file | sed -e 's/_\+/_/')
  echo $f
done;

GNU tr--squeeze-repeats

$ echo foo_______bar | tr --squeeze-repeats _
foo_bar

如果您使用的是 BSD tr ,則可以使用-s代替:

$ echo foo_______bar | tr -s _
foo_bar

Shellcheck -clean 純 shell 代碼應適用於任何符合 POSIX 的 shell,包括bashdash

for file in *; do
    while :; do
        case $file in
            *__*)   file=${file%%__*}_${file#*__};;
            *)      break;;
        esac
    done
    printf '%s\n' "$file"
done
  • ${file%%__*}擴展為$file ,其中第一個__和刪除后的所有字符(例如a__b__c產生a )。
  • ${file#*__}擴展為$file ,其中所有字符直到並包括第一個__被刪除(例如a__b__c產生b__c )。
  • 請參閱為什么 printf 比回聲更好? 解釋為什么printf '%s\n' "$file"代替echo "$file"

暫無
暫無

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

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