![](/img/trans.png)
[英]shell script which will move all executable files in the current directory to a seperate folder
[英]Shell script - move files into folder
假設一個特定的命令生成了幾個文件(我不知道這些文件的名稱)。 我想將這些文件移到新文件夾中。 如何在Shell腳本中執行此操作?
我不能使用:
#!/bin/bash
mkdir newfolder
command
mv * newfolder
因為cwd也包含許多其他文件。
第一個問題是您是否可以僅使用newfolder
作為當前目錄運行command
以在其開頭的正確位置生成文件:
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
如果要將它們移到子文件夾中:
mv `find . -type f -maxdepth 1` newfolder
設置-maxdepth 1
只會在當前目錄中找到文件,而不會遞歸。 傳遞-type f
表示“查找所有文件”(“ d”分別表示“查找所有目錄”)。
假設您的命令輸出的名稱每行一個,該腳本將起作用。
my_command | xargs -I {} mv -t "$dest_dir" {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.