mv:移动和重命名

xiaohai 2021-05-05 17:05:12 1767人围观 标签: Linux 
简介mv命令可以理解为move的缩写,其功能是移动或重命名文件;
命令说明:

mv命令可以理解为move的缩写,其功能是移动或重命名文件;

语法格式:

mv [option] [source] [dest]
mv [选项] [源文件] [目标文件]

参数选项:
  • -f:若目标文件已经存在,则不会询问而是直接覆盖
  • -i:或目标文件已经存在,则会询问是否覆盖
  • -n:不覆盖已经存在的文件
  • -t:指定mv的目标文件,适用于移动多个文件到一个目录的情况,此时目标目录在前,源文件灾后,和cp命令的-t选项功能一直
  • -u:在源文件比目标文件新,或目标文件不存在才进行移动
示例:
[root@localhost test]# ls
dir1  file10.txt  file1.txt  file2.txt  file3.txt  file4.txt  file5.txt  file6.txt  file7.txt  file8.txt  file9.txt

1、移动文件
[root@localhost test]# mv file1.txt dir1/
[root@localhost test]# ls
dir1  file10.txt  file2.txt  file3.txt  file4.txt  file5.txt  file6.txt  file7.txt  file8.txt  file9.txt
[root@localhost test]# ls dir1/
file1.txt

2、移动多个文件
[root@localhost test]# mv file2.txt file3.txt dir1/
[root@localhost test]# ls
dir1  file10.txt  file4.txt  file5.txt  file6.txt  file7.txt  file8.txt  file9.txt
[root@localhost test]# ls dir1/
file1.txt  file2.txt  file3.txt

3、将源文件和目标调换移动到文件目录(-t参数)
[root@localhost test]# mv -t dir1/ file4.txt file5.txt 
[root@localhost test]# ls
dir1  file10.txt  file6.txt  file7.txt  file8.txt  file9.txt
[root@localhost test]# ls dir1/
file1.txt  file2.txt  file3.txt  file4.txt  file5.txt

4、移动目录
[root@localhost test]# ls
dir1  dir2  dir3  dir4  file6.txt  file7.txt  file8.txt  file9.txt
[root@localhost test]# mv dir4 dir5 #移动到不存在的目录,那么就相当重命名
[root@localhost test]# ls
dir1  dir2  dir3  dir5  file6.txt  file7.txt  file8.txt  file9.txt


[root@localhost test]# mv dir1 dir2 #移动到存在的目录,则是把目录移动到目标目录中
[root@localhost test]# ls dir2
dir1
[root@localhost test]# mv dir3/ dir2/ #加上/不影响结果
[root@localhost test]# tree dir2
dir2
├── dir1
│   ├── file1.txt
│   ├── file2.txt
│   ├── file3.txt
│   ├── file4.txt
│   └── file5.txt
└── dir3

2 directories, 5 files

[root@localhost test]# mv dir2/dir1/* dir5 #将目录下的所有文件移动到目标目录下
[root@localhost test]# tree
.
├── dir2
│   ├── dir1
│   └── dir3
├── dir5
│   ├── file10.txt
│   ├── file1.txt
│   ├── file2.txt
│   ├── file3.txt
│   ├── file4.txt
│   └── file5.txt
├── file6.txt
├── file7.txt
├── file8.txt
└── file9.txt

4 directories, 10 files