I select some text and copy it using Ctrl + c. Now the text is in the system clipboard. I can paste this code using Ctrl + v in a file and run wc for the file to check the count of characters, lines and words.

But if I want to count the characters of the text in the clipboard without saving this in a file, is there a solution?


You would need to release the clipboard contents somehow. Avoiding files can be done via a pipeline. For that there exists the xclip utility. It is not installed by default, so unless another program installed it as a dependency you may want to run

sudo apt-get install xclip

Once you install it, you can do

xclip -o sel clip | wc

Note that there exists more than one clipboard aka selection in Linux, hence why the use of -o sel clip flags. Of course, with use of a pipeline this avoids use of intermediate files as requested in the question.

Another side benefit of this utility is that you can use this utility not just in a GUI terminal, but within any virtual tty console by appending DISPLAY=:0 to the beginning of the command (or the other appropriate display, if your X Window aka GUI server is configured for more than one display). See the related post here on that same topic. Thus, you avoid using keyboard shortcuts for releasing clipboard contents, and you can write scripts that use the clipboard in a more powerful way.

There is also another utility called xsel which operates in a similar fashion. You can read about it in a related post.

  • result shows 0 0 0 – alhelal Dec 31 '19 at 11:16
  • Clipboard may have been overwritten or not copied well. It's OK, try copying text again and run the command – Sergiy Kolodyazhnyy Dec 31 '19 at 21:06
  • it's working now – alhelal Jan 2 '20 at 8:00

One solution is 'echo'ing the clipboard content and pass the content to wc:

$ echo -n "your text" | wc
  0 2 9

0 newline, 2 word and 9 characters.

As your text is inside your clipboard, you can paste the content in the terminal easily using Ctrl+Shift+v.

  • 1
    Not if the content has shell-sensitive stuff. This is a fragile, and potentially dangerous, solution. – Lightness Races in Orbit Dec 31 '19 at 15:02
  • @LightnessRaceswithMonica somewhat safer: wc <<'EOF', especially with bracketed paste. – D. Ben Knoble Dec 31 '19 at 18:50
  • Or just wc and enter, paste, then ctrl-D to end the text. wc then displays the counts. – WGroleau Jan 1 '20 at 1:45
  • Unless there is a ^D in the text – Lightness Races in Orbit Jan 1 '20 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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