27

In Bash Emacs mode, is there any way to delete till the previous slash character?

For example, if I entered the command cp /usr/local/bin/reallylongincorrectfolder /home/myname/reallylong_and_correct_path and want to just delete the reallylongincorrectfolder, is there any shortcut?

This is a very common scenario for me in Bash.

Something like dF<char> in vi?

Matthias Braun
  • 1,162
  • 1
  • 17
  • 29
woodstok
  • 931
  • 1
  • 11
  • 23

3 Answers3

18

Alt-Backspace and Ctrl-w are commonly mapped to backward-kill-word, which does that. If you want to find out what it's mapped to on your system (if anything), run bind -P | grep '^backward-kill-word'.

As explained by @Barmar, this is different from unix-word-rubout, which removes to the previous space boundary.

l0b0
  • 7,171
  • 4
  • 33
  • 54
  • 2
    But that will kill the entire word.. I want to kill only till the last slash – woodstok Jun 11 '13 at 08:59
  • It does remove only to the last slash here. Slash is one of the default word separators. [Are you sure you're using Bash?](http://stackoverflow.com/questions/444951/zsh-stop-backward-kill-word-on-directory-delimiter) – l0b0 Jun 11 '13 at 09:01
  • My bad.. Alt-Backspace does remove it till the last slash.What is the difference between ALt-BackSpace and Ctrl-W ? – woodstok Jun 11 '13 at 09:47
  • 3
    Ctl-w is normally bound to `unix-word-rubout`: _Kill the word behind point, using white space as a word boundary._ – Barmar Jun 11 '13 at 10:31
  • 2
    This doesn't exactly work. "Words are composed of alphanumeric characters (letters and digits)". Hence it'll stop at much more than just slashes. The default-unbound `unix-filename-rubout` is slightly better, since it'll stop at white space and slash. – Sparhawk May 04 '14 at 01:16
  • 3
    `alt` + `backspace` deletes until `/`, thus answering the question. `ctrl` + `w` on the other hand deletes until the previous space. – Matthias Braun Feb 20 '17 at 09:49
  • I couldn't set `backward-kill-word` to `ctrl` + `w` using `bind` or `~/.inputrc` - but this answer did the trick: https://superuser.com/questions/212446/binding-backward-kill-word-to-ctrlw you first need to `stty werase undef` – jaygooby Jun 22 '22 at 09:30
15
bind -P |grep unix-filename-rubout

To test out the keybinding with eg. Ctrl-b:

bind \\C-b:unix-filename-rubout

For permanent usage, add it to ~/.inputrc

user1338062
  • 919
  • 1
  • 9
  • 10
  • 2
    To add it to `~/.inputrc`, add a line like this to that file: `"\C-b": unix-filename-rubout`. To see the effect, you'll have to start a new bash shell (or run some other program that uses the GNU readline library). – Croad Langshan Jul 29 '18 at 10:50
12

Put this in your .inputrc and start a new shell:

C-b:unix-filename-rubout

Ctrl-b now erases backwards to the next slash.

Nirvana!

Don't forget Ctrl-XCtrl-E will launch your editor so you can edit a complicated command line comfortably.

Greg Bell
  • 495
  • 7
  • 15