簡體   English   中英

Shell腳本-將文件移動到文件夾

[英]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”分別表示“查找所有目錄”)。

使用模式匹配:

  $ 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

這里毫不客氣地獲取示例,您可以其中找到一些更有用的信息。

假設您的命令輸出的名稱每行一個,該腳本將起作用。

my_command | xargs -I {} mv -t "$dest_dir" {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM