現在の時刻+以前の最新ファイルと同じ月のタイムスタンプを持つすべてのファイルを保持し、ディレクトリ内の残りのファイルを削除するシェルスクリプトが必要です。
ディレクトリに保存されているすべてのファイル名は、name$timestamp.extension
次のように構成されます。
timestamp=`date "+%Y%m%d-%H%M%S"`
つまり、ディレクトリに次のファイルがある場合を意味します。
name161214-082211.gz
name161202-082211.gz
name161020-082211.gz
name161003-082211.gz
name161001-082211.gz
このコードを実行した後、ディレクトリに残っているファイルは次のとおりです。
name161214-082211.gz
name161202-082211.gz
name161020-082211.gz
PS。シェルにとても新しいものです。あなたは動作するコードが欲しいだけでなく、学ぶことができるようにしたいです。その場合はコードも説明してください。ありがとうございます!
ベストアンサー1
君とzsh
似たようなことができる
# get current date (YYMM) in a variable
crd=$(date "+%y%m")
# use a function to extract the 13 chars that make up the timestamp
dtts() REPLY=${${REPLY%%.*}: -13}
# sort file names by the timestamp in descending order, exclude the ones with the
# same YYMM as the current date and set the remaining file names as arguments
set -- *(.O+dtts^e_'[[ "${${REPLY%%.*}: -13:4}" == "$crd" ]]'_)
# remove the first item from the list (i.e. the last one before current month)
shift
# print the remaining file names
print -rl -- "$@"
これはパラメータ拡張を使用し、グローバル予選:最初にタイムスタンプに基づいて降順にソートされた関数(.)を使用して一般的なファイルを選択し
、タイムスタンプが現在の年と月と一致する場合(つまり、引用符内の式がtrueを返す場合)、否定文字列ファイルの選択を解除します。リストから最初の項目を削除し(名前は降順でソートされるため、これは今月より前の最新のタイムスタンプになります)、結果が満足のいくものに置き換えます。O
dtts
e
^e_'[[ "${${REPLY%%.*}: -13:4}" == "$crd" ]]'_
shift
print -rl
rm