3

次のような名前のファイルがいくつかあります。

file1.c.keep.apple

file2.c.keep.apple

引数としてサフィックス (この場合は ) を渡すシェル スクリプトを作成しようとしています。appleこれにより、すべてのファイルの名前が変更され、.keep.apple.

実行例:

script.sh apple

上記のファイルの名前が次のように変更されます

file1.c

file2.c

これまでのところ、私は

 #! /bin/sh
 find . -type f -name \'*.keep.$1\' -print0 | xargs -0 rename 's/\(.keep.*)$//'

ファイルの名前は変更されません。私はそのfind部分が正しいことを知っています。名前の変更の正規表現が間違っていると思います。スクリプトを希望どおりに動作させるにはどうすればよいですか?

4

6 に答える 6

4

私はそのfind部分が正しいことを知っています

そうではないことを除いて。

find . -type f -name "*.keep.$1" -print0 | ...
于 2013-01-04T19:53:00.270 に答える
3

更新、おそらくこれを試してください:

#!/bin/bash

SUFFIX=$1;

find . -type f -name "*keep.${SUFFIX}" | while read -r file;
do 
    nfile=`echo $file | sed "s/\.keep\.${SUFFIX}//g"`; 
    mv "$file" "$nfile" 2>/dev/null; 
done

ここで実行されています:

jgalley@jgalley-debian:/test5$ cat replace.sh 
#!/bin/bash

SUFFIX=$1;

find . -type f -name "*keep.${SUFFIX}" | while read -r file;
do 
    nfile=`echo $file | sed "s/\.keep\.${SUFFIX}//g"`; 
    mv "$file" "$nfile" 2>/dev/null; 
done
jgalley@jgalley-debian:/test5$ find .
.
./-filewithadash.keep.apple
./dir1
./dir1/file
./dir1/file2.keep.orange
./dir2
./dir2/file2
./file with spaces
./file.keep.orange
./file.keep.somethingelse.apple
./file.orange
./replace.sh
jgalley@jgalley-debian:/test5$ ./replace.sh apple
jgalley@jgalley-debian:/test5$ find .
.
./-filewithadash
./dir1
./dir1/file
./dir1/file2.keep.orange
./dir2
./dir2/file2
./file with spaces
./file.keep.orange
./file.keep.somethingelse.apple
./file.orange
./replace.sh
jgalley@jgalley-debian:/test5$ 
于 2013-01-04T19:57:07.363 に答える
1

bash と bash のバージョンが 4 以上 (globstar をサポート) であると想定できる場合は、bash のみのクリーンなソリューションを次に示します。

#!/usr/bin/env bash

(($#)) || exit 1

shopt -s globstar nullglob
for f in **/*.keep."$1"; do
    mv -- "$f" "${f%.keep.$1}"
done

findまたは、ループを使用したソリューションをwhile read次に示します (GNU または BSD の検索を想定しています)。

find . -type f -name "*.keep.$1" -print0 | while IFS= read -r -d '' f; do
    mv -- "$f" "${f%.keep.$1}"
done

このソリューションの詳細については、http://mywiki.wooledge.org/BashFAQ/030を参照してください。

また、あなたがしようとしていることをfindwith で実装することができます-exec:

find . -type f -name "*.keep.$1" -exec sh -c 'mv -- "$2" "${2%.keep.$1}"' _ "$1" {} ';'
于 2013-01-05T20:46:48.267 に答える
1

私はあなたが必要だと思います:

find . -type f -name "*.keep.$1" -print0 | xargs -0 rename "s/\.keep\.$1$//"

次の制限事項に注意してください。

  • 名前の変更は、どこでも利用できるとは限りません。
  • find -print0およびxargs -0すべての Unix で使用できるとは限らない GNU 拡張機能です。
  • 最初のパラメーターに正規表現にとって特別な文字が含まれている場合、結果は希望どおりにならない可能性があります。(例yourscript "a*e")
于 2013-01-04T20:13:37.110 に答える
0

これはどう?

[spatel@us tmp]$ x=aa.bb.cc
[spatel@us tmp]$ y=${x%.cc}
[spatel@us tmp]$ echo $y
aa.bb


[spatel@us tmp]$ x=aa.bb.cc
[spatel@us tmp]$ y=${x%.bb.cc}
[spatel@us tmp]$ echo $y
aa
于 2013-01-04T20:23:28.287 に答える