cp /abc/section/AAAooo/CBACenter/slack_2010-05-1.txt ${OUTPUT_FILE_NAME}

How do I perform a count within this script and only output the count? Somehow I need to be able to count rows within this shell script and output the count value. I think I may need to do something like this:

cat filename.txt | wc -l

However, I am not sure how to input it correctly so the syntax works out fine. It keeps giving me an error. The count needs to be done in this line:

cp /abc/section/AAAooo/CBACenter/slack_2010-05-1.txt ${OUTPUT_FILE_NAME}
  • 2
    Which file do you ant to count the lines of? The script being run or the file being copied? – jesse_b Nov 15 '18 at 21:27
  • The file being copied – ihoaxed Nov 15 '18 at 22:12
  • @ihoaxed The (standard) cp command does not put the file contents through the pipe. It will just copy the file, producing no output (save for erroring). You will need to later do wc -l /path/to/your/file.txt – Stan Strum Nov 15 '18 at 22:18
  • Actually, errors won't go to output either (redirection notwithstanding); they go do standard error. – DopeGhoti Nov 15 '18 at 22:20
  • You might want to edit your question, adding the command that gives you an error and the actual text of the error. It would probably make easier to understand what exactly is the result you are expecting. – fra-san Nov 15 '18 at 23:12

You can do it by below method

cp $1 $2
wc -l $2

Above script will copy the $1(file1) content to $2(file2) and after being copied to second file. it will print count of lines in file2

We should execute script as below

sh scriptname file1 file2


cp (normally) does not output anything. If you use cp -v, it will output the name of each file it is copying, but not their contents.

UNIX-like environments are generally quite good at having tools that do precisely one job, and do it well. Counting the lines in a file (the job of wc) is not in the demesne of a tool whose job is to copy files from one location to another (e. g. cp).

If you want to count the lines in a file and also copy it, you need to do these two separate tasks separately.

$ cp /old/path/to/file /new/path/to/file
$ filelength="$( wc -l < /path/to/file )"
  • 1
    But not with UUOC? Try wc -l < file – RudiC Nov 16 '18 at 8:59
  • I forgot about indirection. I originally had wc -l file | awk '{print $1}' to strip out the filename, but indirection is much better. Good catch. – DopeGhoti Nov 16 '18 at 15:50

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