关于linux:每天学一个-Linux-命令18mv

5次阅读

共计 2689 个字符,预计需要花费 7 分钟才能阅读完成。

举荐: 每天学一个 Linux 命令(17):chmod

命令简介

mv 命令用于挪动并重命名文件和目录。或者将文件从一个目录挪动到另一个目录中,如果将一个文件挪动到一个曾经存在的指标文件中,这时指标文件的内容会被此文件内容笼罩。

如果源为文件,而指标为目录,mv 将进行文件的地位挪动。如果源为目录,则指标只能是目录(不能为文件),mv 将进行目录的重命令名。

mv 命令挪动文件时,在指标不同的状况下,会有上面 4 种不同的后果:

  • 如果指标是指定的某一个具体门路,则源文件会被挪动到此目录下,且文件名不变。
  • 如果指标不是目录,则源文件名(只能有一个)会变为此指标文件名,如果存在同名文件,则会笼罩己存在的同名文件。
  • 如果源文件和指标文件在同一个目录下,mv 的作用就是批改文件名。
  • 当指标是目录时,源文件或目录能够是多个,这时所有的源文件都会被移至目标目录下。且所有的文件都将保留以前的文件名。

语法格局

mv [选项] 源文件或目录 指标文件或目录
mv [options] source destination

选项阐明

-b   #当文件存在时,笼罩前,为其创立一个备份
-f   #如果移到的文件或目录与指标反复,则间接笼罩
-i   #交互式操作,笼罩前会提醒用户进行确认操作,用户通过输出 Y / N 来确认是否笼罩
-u   #若指标文件已存在,且与需挪动的文件同名,只有在源文件比指标文件较新时,才会更新指标文件
-t   #指定 mv 的目标目录,此选项应用于挪动多个文件到一个目录的状况,此时指标文件在前,源文件在后。-S< 后缀 >:# 为备份文件指定后缀,而不应用默认的后缀(删除源文件中的斜杠“/”)-n  #不笼罩任何现有文件
-T  #将指标当作一般文件,而不是目录
-v  #具体输入命令的执行过程

利用举例

# 挪动文件到目标目录
[root@centos7 testdir]# ll
total 0
-rw-r--r-- 1 root root 0 Feb 25  2021 filetest
-rw-r--r-- 1 root root 0 Feb 25  2021 testfile
[root@centos7 ~]# mv mingongge.txt testdir/
[root@centos7 ~]# ll testdir/
total 0
-rw-r--r-- 1 root root 0 Feb 25  2021 filetest
-rw-r--r-- 1 root root 0 Jan  2 08:43 mingongge.txt
-rw-r--r-- 1 root root 0 Feb 25  2021 testfile
#挪动并重命令文件
[root@centos7 testdir]# mv mingongge.txt test/mingongge
[root@centos7 testdir]# ll test/
total 0
-rw-r--r-- 1 root root 0 Jan  2 08:50 mingongge

如果指标地位有同名文件,咱们不心愿它被笼罩,能够加上 - n 选项。

[root@centos7 testdir]# ll *.txt dir/*.txt
-rw-r--r-- 1 root root 0 Jan  2 08:58 dir/test1.txt
-rw-r--r-- 1 root root 0 Jan  2 08:58 dir/test2.txt
-rw-r--r-- 1 root root 0 Jan  2 09:03 test1.txt
-rw-r--r-- 1 root root 0 Jan  2 08:57 test2.txt
-rw-r--r-- 1 root root 0 Jan  2 09:03 test3.txt
[root@centos7 testdir]# mv -nv *.txt dir/‘test3.txt’->‘dir/test3.txt’#目标目录中没有 test3.txt 文件,所以挪动胜利
[root@centos7 testdir]# ll
total 0
drwxr-xr-x 2 root root 57 Jan  2 09:04 dir
-rw-r--r-- 1 root root  0 Jan  2 09:03 test1.txt
-rw-r--r-- 1 root root  0 Jan  2 08:57 test2.txt

备份性能

# 如果 test2.txt 存在,它将会被重命令为 test2.txt, 原来的文件会被备份
[root@centos7 dir]# cat test1.txt 
1
[root@centos7 dir]# cat test2.txt 
2
[root@centos7 dir]# mv -b test1.txt test2.txt
mv: overwrite‘test2.txt’? y
[root@centos7 dir]# ll
total 12
-rw-r--r-- 1 root root 2 Jan  2 09:12 test2.txt
-rw-r--r-- 1 root root 2 Jan  2 09:12 test2.txt~
-rw-r--r-- 1 root root 2 Jan  2 09:12 test3.txt
[root@centos7 dir]# cat test2.txt
1
[root@centos7 dir]# cat test2.txt~
2
#如果 test3.txt 存在,它将会被重命令为 test3.txt.bak
[root@centos7 dir]# mv -b --suffix=.bak test2.txt test3.txt
mv: overwrite‘test3.txt’? y
[root@centos7 dir]# ll
total 12
-rw-r--r-- 1 root root 2 Jan  2 09:12 test2.txt~
-rw-r--r-- 1 root root 2 Jan  2 09:12 test3.txt
-rw-r--r-- 1 root root 2 Jan  2 09:12 test3.txt.bak
[root@centos7 dir]# cat test3.txt
1
[root@centos7 dir]# cat test3.txt.bak 
3

每天学一个 Linux 命令(16):mkdir

每天学一个 Linux 命令(15):man

每天学一个 Linux 命令(14):cat

正文完
 0