If I want to move a file called longfile from /longpath/ to /longpath/morepath/ can I do something like
mv (/longpath)/(longfile) $1/morepath/$2
i.e. can I let the bash know that it should remember a specific part of the input so I can reuse it later in the same input?
(In the above example I use an imaginary remembering command that works by enclosing in parantheses and an imaginary reuse command $ that inserts the content of the groups)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could do this:
mv /longpath/longfile !#:1:h/morepath/
See https://www.gnu.org/software/bash/manual/bashref.html#History-Interaction
!#is the current command:1is the first argument in this command:his the “head” — thinkdirname/morepath/appends that to the head- and you’re moving a file to a directory, so it keeps the same basename.
If you want to alter the “longfile” name, say add a “.txt” extension, you could
mv /longpath/longfile !#:1:h/morepath/!#:1:t.txt
Personally, I would cut and paste with my mouse. In practice I never get much more complicated than !! or !$ or !!:gs/foo/bar/
Method 2
You could also do this with brace expansion:
mv /longpath/{,morepath/}longfile
The shell expands this so that the mv command sees it the same as:
mv /longpath/longfile /longpath/morepath/longfile
Method 3
If you are for more efficient typing in command line, you may find various readline shortcut useful. Readline is already built-in your shell. For your paricular case you could yank/delete parts of your line and then recall them from readline killiring.
Moreover, if you have EDITOR environmnent variable set to your favorite editor, then Ctrl-X,Ctrl-E will copy your current command line into editor window where you can have all the editor power to modify your line. Once completed, you save/exit from the editor and the line gets executed in your shell.
Method 4
For something like the specific case you are asking about, you can also use a subshell.
mv (/longpath)/(longfile) $1/morepath/$2
becomes
( cd /longpath; mv longfile morepath/ )
while keeping your current working directory in the shell you are working in.
This isn’t entirely dissimilar to Wildcard’s suggestion of using shell expansion but can be done for more complex situations than a simple something-here-in-one-argument-only can readily support.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0