Bash循环将目录从一个位置更改到另一个位置。

huangapple go评论54阅读模式
英文:

Bash foor loop change the directory from one location to anther location

问题

这是我的目录树。每个目录 A、B、C 都包含与用户名对应的特定 user.txt 文件。

现在我想切换到每个目录 A、B、C,并需要将 usera.txt、userb.txt、userc.txt 分别压缩到相应的文件夹中,并在取得压缩文件后从目录中删除源文件(.txt 文件)。

我可以看到上面的脚本不是一个可重用的代码,并且也存在重复的循环。你能指导我如何以更好的方式处理吗?

注意:如果可能的话,我们也可以递归地压缩每个目录和文件,就像下面这样。
英文:

Here the my directory Tree. Each directory A, B, C contains specific user.txt file respective to the user name.

Now I want to switch to each directory A, B, C and need to zip only usera.txt, userb.txt, userc.txt into the respective folder and delete the source file (.txt file) from the directory after taking zip file.

┌──(root㉿DESKTOP-1OOLTMI)-[/home/gowmi]
└─# tree
.
├── UserA
│   └── usera.txt
├── UserB
│   └── userb.txt
└── UserC
    └── userc.txt

4 directories, 3 files

my for loop

PATH1=/home/gowmi/UserA/*

for file in $PATH1*; 
do
	zip ${file%.*}.zip $file -mT .; 
done

PATH2=/home/gowmi/UserB/*

for file in $PATH2*; 
do
	zip ${file%.*}.zip $file -mT .; 
done

PATH3=/home/gowmi/UserC/*

for file in $PATH3*; 
do
	zip ${file%.*}.zip $file -mT .; 
done

I can see above script is not a reusable and i can see we have code duplication as well for repeating the for loop. Can you please some guide me how i can make it better way.

NOTE: and also if its possible we can take recursively zip file each directory and file as well. like below.

答案1

得分: 1

循环可以嵌套。

第一步将是:

for path in /home/gowmi/UserA /home/gowmi/UserB /home/gowmi/UserC ; do
    for file in $path/* ; do 
        zip ${file%.*}.zip $file -mT .; 
    done
done

当您有更多用户时,您可以:

for path in /home/gowmi/User* ; do
英文:

Loops can nest.

The first step would be:

for path in /home/gowmi/UserA /home/gowmi/UserB /home/gowmi/UserC ; do
    for file in $path/* ; do 
        zip ${file%.*}.zip $file -mT .; 
    done
done

When you get more users, you can:

for path in /home/gowmi/User* ; do

huangapple
  • 本文由 发表于 2023年5月7日 17:52:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定