Is there any shortcut to reference the path of the first argument in a MV command?

你离开我真会死。 提交于 2019-12-29 05:21:11

问题


I often find myself using mv to rename a file. E.g.

mv app/models/keywords_builder.rb app/models/keywords_generator.rb

Doing so I need to write (ok, tab complete) the path for the second parameter. In this example it isn't too bad but sometimes the path is deeply nested and it seems like quite a bit of extra typing.

Is there a more efficient way to do this?


回答1:


You can use history expansion like this:

mv app/modules/keywords_builder.rb !#^:h/keywords_generator.rb
  1. ! introduces history expansion.
  2. # refers to the command currently being typed
  3. ^ means the first argument
  4. :h is a modifier to get the "head", i.e. the directory without the file part

It's supported in bash and zsh.

Docs:

  • bash history expansion
  • zsh history expansion



回答2:


And another way: brace expansion.

mv app/models/keywords_{builder,generator}.rb

In general,

before{FIRST,SECOND}after

expands to

beforeFIRSTafter beforeSECONDafter

So it's also useful for other renames, e.g.

mv somefile{,.bak}

expands to

mv somefile somefile.bak

It works in bash and zsh.

More examples:

  • Eric Bergen > Bash Brace Expansion
  • Bash Brace Expansion | Linux Journal



回答3:


One way is to type the first file name and a space, then press Ctrl+w to delete it. Then press Ctrl+y twice to get two copies of the file name. Then edit the second copy.

For example,

mv app/models/keywords_builder.rb <Ctrl+W><Ctrl+Y><Ctrl+Y><edit as needed>



回答4:


or cd apps/models && mv keywords_builder.rb keywords_generator.rb && cd -




回答5:


Combined answers of Mikel and geekosaur with additonal use of ":p"

use brace expansion to avoid first argument repetition:

mv -iv {,old_}readme.txt # 'readme.txt' -> 'old_readme.txt'

mv -iv file{,.backup} # 'file' -> 'file.backup'

use history expansion to avoid first argument repetition:

mv -iv "system file" !#$.backup # 'system file' -> 'system file.backup'

the filename can be printed using the "p" designator for further edition:

mv -iv "file with a long name" !#$:p

then press "↑" to edit the command



来源:https://stackoverflow.com/questions/5505827/is-there-any-shortcut-to-reference-the-path-of-the-first-argument-in-a-mv-comman

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!