-2

I am trying to create a file and it looks like the vi editor is adding a $ at the end of each line. I don't know what's causing this or how to prevent vi from doing it.

vi file.txt
12345
abcde

cat -v -e file.txt
12345$
abcde$

wc file.txt
2 2 12

I don't want those $ symbols at the end; they break my automation files which depend on character count. Why would word count shows 12 characters when in fact each line has 5 characters?

VIM version 7.4.629

  • 6
    The $ symbols are added bycat because you used the -e flag (show line endings) – steeldriver Jun 21 '16 at 23:18
  • 1
    No, they are not added by cat. See the updated question – ayrton_senna Jun 21 '16 at 23:19
  • 2
    wc includes newlines (linefeed characters) in its count – steeldriver Jun 21 '16 at 23:27
  • 3
    Your "automation files" are perhaps overly fragile; have you considered posting them on Code Review? – Wildcard Jun 21 '16 at 23:59
5

@steeldriver's comment is correct: cat shows line-endings with $ (as vi might if you asked it nicely, using ":set list"). The extra character per line is the newline (an invisible character at the end of each line of text).

If you want only a count of the printable text, you could filter the file before processing it with wc, e.g., using tr with the -d option. Here is a script which counts itself as an example:

#!/bin/sh
cat $0 |wc
cat $0 | tr -d '\r\n\t' | wc
cat $0 | tr -d '[:cntrl:]' |wc

though the last line is possibly not portable enough for your use (it is in POSIX, in the extended section). But it will run on anything you're likely to be using, based on the clues in the rationale.

  • 1
    I understand cat -v -e shows extra characters including the unprintable characters. But it does not explain me as to why word count is not coming out as 10. – ayrton_senna Jun 21 '16 at 23:27
  • 3
    wc is showing the total number of characters in the file: 5 visible characters for each of 2 lines, plus one extra invisible character (per line). 2 times (5 + 1) = 12. – Thomas Dickey Jun 21 '16 at 23:29
  • 1
    ok, thanks, so how whould i get the character count of only printable characters in file ? – ayrton_senna Jun 21 '16 at 23: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.