0

"Append to the file the following commands that when this file is executed it will do the following:

4) Display This file has x lines

5) Display This file has x words

6) Display this file has x bytes "

I know the command is the variations of wc, but I can't figure out how to add that command to the script, only how to run it .

  • simply at beginning of script add lines witch will count necessary values, and print them. or prepare wrapper, that will get script name as param, then it will count those values, print those values, then execute script – darvark Mar 19 '17 at 15:46
  • 1
    Why don't you show us what you have tried, the result you got, and the result you were looking for? It's very hard to recommend how to fix your code if your code is not included in your question. – ghoti Mar 19 '17 at 15:54

2 Answers2

0
lines=$(wc -l $0)
echo This file has $lines lines
words=$(wc -w $0)
echo This file has $words words
bytes=$(wc -b $0)
echo This file has $bytes bytes

should do the trick.

Hellmar Becker
  • 2,824
  • 12
  • 18
0

It's a one-liner, using bash process substitution.

$ read lines words bytes filename < <(wc /path/to/file)

Output is also a one-liner, and you can leverage bash arrays if you like. Here's a real example:

$ read -a arr < <(wc /etc/passwd);
$ declare -p arr
declare -a arr=([0]="96" [1]="265" [2]="5925" [3]="/etc/passwd")
$ unset arr[3]
$ printf 'lines: %d\nwords: %d\nbytes: %d\n' "${arr[@]}"
lines: 96
words: 265
bytes: 5925

Similar results in POSIX shell might be achieved using a temporary file:

$ tmp=$(mktemp /tmp/foo.XXXX)
$ wc /etc/passwd > $tmp
$ read lines words bytes filename < $tmp
$ rm $tmp
$ printf 'lines: %d\nwords: %d\nbytes: %d\n' "$lines" "$words" "$bytes"
lines: 96
words: 265
bytes: 5925

Or you can fetch the data as a here-doc without the temporary file:

$ read lines words bytes filename <<EOT
> $(wc /etc/passwd)
> EOT

(Obviously, you'd strip the interactive prompts if you were to script this.)

Note that printf recommended over echo for output, as it is consistent across different operating systems and shells. This excellent post explains some considerations.

Community
  • 1
  • 1
ghoti
  • 45,319
  • 8
  • 65
  • 104