0

What I want to do is basically

cp long/directory/path/file long/directory/path/file-copy

This or similar operations are pretty common. Typing out the whole path twice is obviously awkward, even with auto-completion or copy-paste. There are a couple of simple ways to do it, but none seems ideal:

  • First cd into the directory, then simply cp file file-copy. Least keystrokes, but I end up in the directory, which I didn't really want.
  • Wrap the above in a subshell, sh -c 'cd dir-path; cp file file-copy', to make the cp local. Fair enough, but that means I have to type the commands in a string literal, which disables auto-completion and isn't overall nice.
  • Define the dir as a variable, then just cp "$dir/file" "$dir/file-copy". Can work nicely, but I'm kind of paranoid about namespace pollution...
  • echo dir-path | while read p; do cd "$p"; cp file file-copy; done. Basically combines subshell-wrapping with variable definition, by emulating a lambda-calculus stype let-binding with read. I quite like it, but it's just a bit weird, and involves a lot of extra characters.
  • Anything I can come up with that uses sed 's/file/file-copy/' needs even more boilerplate around it.
  • Open the file with an editor, then save-as. Not well applicable to non-text files, and often resource-costly.

Is there a more elegant alternative? Ideally one that works with mv as well, analogously.

1 Answers1

3

As per this question, you can use:

cp /long/path/to/file{,-copy}

This a shell expansion done by bash (not sure about others), so it will work with any command.

casey
  • 14,754
  • 1
    When you find a question that duplicates another question, please flag it as a duplicate instead of answering it. Use the “flag” button on the question, select “it is a duplicate”, and enter the link to the question. – Gilles 'SO- stop being evil' Dec 14 '13 at 22:54