MacOS – How to copy line without trailing whitespaces in terminal

command linemacosterminal

In OS X 10.11.6, I want to use a line of file paths output from terminal as input to another command. Right now, when I triple click on a line, the line gets selected, but with trailing whitespaces including a new line – this makes it hard to use that path in a command. Here is an example session that illustrates the problem:

~/testdir : ls -1 # there is a single file called "foo bar" 
foo bar
# I selected the above output line with a triple click. 
# This selected the line including newline at the end. 
# I copy this to clipboard (Cmd-c). 
# I then call wc below, with an open quote.
# I paste the output(Cmd-v)
# I close the quote in the next line. 
# This gives an error as shown below
~/testdir : wc "foo bar
> "
wc: foo bar
: open: No such file or directory
# Now I use up arrow to recall last line, and delete the whitespace before closing quote
# This works fine
~/testdir : wc "foo bar"
       1       2      12 foo bar

How do I avoid this duplicate effort each time – i.e, how do I select the line without whitespaces, so only foo bar gets selected?

Best Answer

When a line in Terminal contains whitespace there is no method, that I know of, which involves just clicking to highlight the line sans the newline character.

  • You can single-click at the start of the line (or any inception point) you want to copy then press and hold the shift key and single-click the last word, or character, of the line you want copied. This will then not include the newline character when you press commandC to copy it to the Clipboard.

  • You can also double-click the first word, which highlights it, and then press and hold the shift key and single-click the last word, or character, of the line you want copied. This will then not include the newline character when you press commandC to copy it to the Clipboard.

  • Or you can single-click and hold at the start of the line (or any inception point) you want to copy while dragging the cursor to the last character in the line you want to copy. This will then not include the newline character when you press commandC to copy it to the Clipboard. Obviously this last one is probably not exactly what you're looking for but was included for completeness.