gpt4 book ai didi

linux - Shell 脚本 - 将文件移动到文件夹中

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:33 25 4
gpt4 key购买 nike

假设一个特定的命令生成了几个文件(我不知道这些文件的名称)。我想将这些文件移动到一个新文件夹中。如何在 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

关于linux - Shell 脚本 - 将文件移动到文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11223671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com