I sometimes copy-paste paths into the terminal, and often accidentally copy the newline character. For example, I want to find then read the contents of foobar.txt
.
$ locate foobar.txt
/home/sparhawk/Document Directory/foobar.txt
I then select the second line with a triple click. (Oops, it selects the trailing newline too!) Since there is a space in the path, I need to enclose the path in quote marks. Hence type in
$ cat '
and middle-click to paste. This produces
$ cat '/home/sparhawk/Document Directory/foobar.txt
>
since I have inserted a newline before closing the '
. At this point, I cannot press backspace to delete the newline. Is there a way to delete this just-typed newline?
More information
At this point I can either SIGINT
with Ctrl+c, or complete the quote with another '
. Let's say I do the latter.
$ cat '/home/sparhawk/Document Directory/foobar.txt
> '
cat: /home/sparhawk/Document Directory/foobar.txt
: No such file or directory
which makes sense, as I just typed in a path with newline in it. However, at this point, I can press the up arrow, to load the last command. i.e.
$ cat '/home/sparhawk/Document Directory/foobar.txt
'
At this point, I can press backspace twice to delete the newline. (N.B. there is no >
in the second from-history example.)
Best Answer
Bash uses GNU Readline Library for command-line input and editing. Unfortunately this library processes the input only line by line. The
readline()
call returns after finishing the line by pressing Enter. Next line (after showing the$PS2
">
" prompt) is processed by a separatereadline()
call.When you go back in the editing history to a multi-line input Readline treats the input as a single "line" with newlines (the
$PS2
prompts are not displayed) so you can edit the whole multi-line input as you described.I use the following trick to solve the problem you presented: When I have input with unwanted newline I cancel it by pressing Ctrl+c. Then I return to the cancelled input by pressing ↑ (or Ctrl+p). Then I can remove the newline by Backspace and do other edits.
Input with unwanted newline at the end, pressing Ctrl+c:
After pressing ↑ the input returns event without the trailing newline: