特定のコマンドがいくつかのファイルを生成するとします (これらのファイルの名前はわかりません)。これらのファイルを新しいフォルダーに移動したい。シェルスクリプトでそれを行う方法は?
私は使用できません:
#!/bin/bash
mkdir newfolder
command
mv * newfolder
cwdには他の多くのファイルも含まれているためです。
最初の質問は、現在のディレクトリとして実行command
しnewfolder
て、最初の適切な場所にファイルを生成できるかということです。
mkdir newfolder
cd newfolder
command
またはcommand
、パスにない場合:
mkdir newfolder
cd newfolder
../command
これができない場合は、前後のファイルのリストを取得して比較する必要があります。これを行うエレガントでない方法は、次のようになります。
# Make sure before.txt is in the before list so it isn't in the list of new files
touch before.txt
# Capture the files before the command
ls -1 > before.txt
# Run the command
command
# Capture the list of files after
ls -1 > after.txt
# Use diff to compare the lists, only printing new entries
NEWFILES=`diff --old-line-format="" --unchanged-line-format="" --new-line-format="%l " before.txt after.txt`
# Remove our temporary files
rm before.txt after.txt
# Move the files to the new folder
mkdir newfolder
mv $NEWFILES newfolder
パターン マッチングを使用します。
$ ls *.jpg # List all JPEG files
$ ls ?.jpg # List JPEG files with 1 char names (eg a.jpg, 1.jpg)
$ rm [A-Z]*.jpg # Remove JPEG files that start with a capital letter
ここから恥知らずに取られた例で、それに関するより有用な情報を見つけることができます。
それらをサブフォルダーに移動したい場合:
mv `find . -type f -maxdepth 1` newfolder
a を設定する-maxdepth 1
と、現在のディレクトリ内のファイルのみが検索され、再帰は行われません。渡す-type f
ことは、「すべてのファイルを検索する」ことを意味します (「d」は、それぞれ「すべてのディレクトリを検索する」ことを意味します)。
コマンドが名前を 1 行に 1 つずつ出力すると仮定すると、このスクリプトは機能します。
my_command | xargs -I {} mv -t "$dest_dir" {}