I've been trying to do this for hours now,

I have a file that have this data, let's call it data1:


I want to add a count, along with a comma to the end of the line of this data. Let's assume that I'm counting the number of lines of data1 , which is 1 line.

echo ", $(wc -l < data1 | bc)"

I want my output to be:


I've tried echo, printf, some awk( I still don't get this much), cat.

4 Answers 4


With awk

awk '{$0=$0","NR}1' data1

Assuming a POSIX file, echo "$(head -c-1 data1)","$(wc -l <data1)" will output what you want. head removes the trailing newline.


Use sed to append the number to the last line:

STRING=`echo "$(wc -l < data1 | bc)"` && sed -i '$s/^\(.*\)$/\1,'"$STRING"'/' data1
$ cat data1 

First part saves the number of lines to the variable STRING and the sed takes the last line and appends the , and content of $STRING variable to the end of the line.


The paste command is used to add columns:

$ wc -l <data1 | paste -d, file -
test1,test2,test3,       1

This is literally what you asked for; the output of wc is added to the end of the line of the file. The output of wc has whitespace at the start of the line, which is why you get the spacing you get here.

To remove this whitespace:

$ wc -l <data1 | sed 's/^ *//' | paste -d, file -

The paste command is here used with -d, which makes it insert a comma between the old and the new columns. The - signals that the new columns should be read from standard input rather than from a file. The standard input comes from wc -l which counts the number of lines in the file.

The variation with sed simply takes the wc output and removes any space characters at the start of the line.

Using bash process substitution:

paste -d, file <( wc -l <data1 | sed 's/^ *//' )

Here, the process substitution, <( ... ), takes the place of -.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .