大网数据广告活动
服务器运维问答

Linux mv file with long name

· 52CE 我爱测

In Linux I sometimes rename files like this: mv dir1/dir2/dir3/file.txt dir1/dir2/dir3/file.txt.old Note that I want to just rename the file, not move it to another directory. Is there a command that would allow me to do a shorth…

问题原文

原帖链接 · santiago arizti · CC BY-SA 3.0

In Linux I sometimes rename files like this:

mv dir1/dir2/dir3/file.txt  dir1/dir2/dir3/file.txt.old

Note that I want to just rename the file, not move it to another directory.

Is there a command that would allow me to do a shorthand version of that command? I am thinking something like:

mv dir1/dir2/dir3/file.txt  file.txt.old

or maybe even something like (to just append to the name):

mv dir1/dir2/dir3/file.txt  {}.old

My goal is not to have to specify the complete path again.

I know those "examples" I wrote don't work, but it is just an idea of what I want to accomplish.

I don't want to have to cd in to the directory.

社区高分解答

原帖链接 · Law29 · CC BY-SA 3.0

I like @archemar's solution of using {} expansion, because you can use it when you have already started your command line. Here are some other possibilities for completeness:

F="dir1/dir2/dir3/file.txt" ; mv "$F" "$F.old"

(quotes are only necessary if you have spaces or other word-breaking characters in the name)

mymv() {
    mv "$1/$2" "$1/$3"
}

mymv dir1/dir2/dir3 file.txt file.txt.old
mymv dir5/dir6/dir7 file.txt file.txt.old

Notes:

  • This is bash syntax, you might be using another shell
  • mymv can be any reasonable string, I used mymv for "my move".
  • The function definition can be put in your .bash_profile

Another one:

cd dir1/dir2/dir3 ; mv file.txt file.txt.old ; cd -

but

(cd dir1/dir2/dir3/ && exec mv file.txt file.txt.old)

(from @Adam and @CharlesDuffy) is arguably better in case the cd fails.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-01-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。