Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Is there a way I can specify to bash to reuse the item I just previously typed? For instance, if I wanted to rename a file, adding a few characters as a prefix, I want to do something like

$> mv file.txt new_{prev}

and end up with new_file.txt.

Is there such a symbol?

share|improve this question

3 Answers 3

up vote 11 down vote accepted

You can use braces({}), but in a somewhat different way. Within braces, prefix{x,y,z...}suffix, will expand to put each comma-separated piece between prefix and suffix:

$ mv {,new_}file.txt

This will expand to mv file.txt new_file.txt. You can also do this with number or letter ranges, {a..d} will expand to a b c d, {1..4} will expand to 1 2 3 4. You can use only one or the other within a level of braces, but you can nest:

$ echo {a,c,{1..3}}
a c 1 2 3

For more about brace expansion, see this question: brace expansion other commands besides mkdir?

share|improve this answer

You can define an editing function that copies the previous word under the cursor.

copy_preceding_word () {
  local prefix suffix word
  prefix="${READLINE_LINE:0:$READLINE_POINT}"
  suffix="${READLINE_LINE:$READLINE_POINT}"
  if [[ $prefix =~ ([^[:space:]]+)[[:space:]]+[^[:space:]]*$ ]]; then
    word=${BASH_REMATCH[1]}
    READLINE_LINE="$prefix$word$suffix"
    ((READLINE_POINT += ${#word}))
  fi
}
bind -x '"\e\C-_": copy_preceding_word'
share|improve this answer
    
Excellent readline solution! This does exactly what user394 asked for. –  bdowning Jan 28 '12 at 12:59

I have this in my ~/.inputrc:

"\ej": "!#:$\e^"

!# is the current line, $ is the last word, and \e^ is history-expand-line.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.