1

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

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

test1,test2,test3

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:

test1,test2,test3,1

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

1

With awk

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

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

0

Use sed to append the number to the last line:

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

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.

0

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 -
test1,test2,test3,1

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 -.

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.