2017-09-18 27 views
-1

名前の最後に空白があるファイルまたはディレクトリがあります。 シェルで削除することは可能ですか?シェル、名前の末尾に空白を削除します

おかげ

+2

はい、可能です。あなたは何かを試して、コードを掲示し、あなたが持っている問題を示す必要があります –

+0

ファイルの名前を変更しますか? – chepner

+0

@Dejaそうではありません。この質問は、名前ではなくファイルの内容から末尾のスペースを削除することです。 – Aaron

答えて

3
for f in *[[:space:]]; do     # iterate over filenames ending in whitespace 
    [[ -e $f || -L $f ]] || continue   # ignore nonexistent results (ie. empty glob) 
    d=$f          # initialize destination variable 
    while [[ $d = *[[:space:]] ]]; do   # as long as dest variable ends in whitespace 
    d=${d:0:((${#d} - 1))}     # ...trim the last character from it. 
    done 
    printf 'Renaming %q to %q\n' "$f" "$d" >&2 # log what we're going to do 
    mv -- "$f" "$d"       # and do it. 
done 

参照:

  • Parameter expansion、最後の文字(${varname:start:length}位置startから始まる指定された長さのスライスを取る)をトリミングするために使用する構文。
  • Globbingは、空白で終わるファイル名を一覧表示するためのメカニズムです。
  • The classic for loop。グロブ結果を反復処理するために使用されます。

のprintf %q指定子は戻ってその元の文字列の内容にevalするような方法で文字列をフォーマットし、bashの拡張である - したがって、それはname\ または'name 'としてスペースで終わる名前を印刷することができるが、何らかの形で、または別の方法で、空白が読者に見えるようにします。

+1

'extglob'パターンを使用するのではなく、なぜループしていますか?' d = $ {f %% +([[:space:]])} ''または 'd = $ {f /%+([[:space :]])/} ' –

+0

ありがとうございます!完璧に動作:) – Musyanon

0

ここには、外部呼び出しのないネイティブのPOSIXシェルソリューションがあります。

#!/bin/sh 

for file in *[[:space:]]; do   # loop over files/dirs ending in space(s) 
    [ -e "$file" ] || continue   # skip empty results (no-op) 
    new_file="${file%[[:space:]]}"  # save w/out first trailing space char 
    while [ "$file" != "$new_file" ]; do # while the last truncation does nothing 
    file="${file%[[:space:]]}"   # truncate one more trailing space char 
    done 
    # rename, state the action (-v), prompt before overwriting files (-i) 
    mv -vi -- "$file" "$new_file" 
done 
関連する問題