stressed_geek
stressed_geek

Reputation: 2176

How to append number of lines in a text file to the beginning of the file?

I have hundreds of text files in a folder. I am looking for a way to append number of lines in a text file to the beginning of the corresponding text file? Any idea, how to do this quickly for all the files in the folder using Bash?

Upvotes: 0

Views: 641

Answers (3)

Loki Astari
Loki Astari

Reputation: 264631

How about:

for file in *.txt; do
    tmp=$(mktemp -dt "${file}")
    < ${file} wc -l | cat - ${file} > ${tmp}
    mv ${tmp} ${file}
done

Or if you want to do it in parallel:

function AddLineCount {
    tmp=$(mktemp -dt "$1")
    < $1  wc -l | cat - $1 > ${tmp}
    mv ${tmp} $1
}

# With a parallelism of 10
# Assuming your disk has the iops for it.
ls *.txt | xargs -P10 -I^ AddLineCount ^

Update

Modifying file without creating a new one. This relies on some properties of sed which is not a bash built-in and sometime varies between versions. The current command works on my mac

sed -i -e "1s/^/$( wc -l fileName | awk '{print $1}')\\
/" fileName

So doing it in a loop:

for file in *.txt; do

    sed -i -e "1s/^/$(wc -l ${file} | awk '{print $1}')\\
/" ${file}

done

Upvotes: 4

MattSizzle
MattSizzle

Reputation: 3175

The following will do just that with the approriate substitution for the grep to insure you work on the right files.

for i in $(ls |grep ".txt") ; do c=$(wc -l < $i) ; sed -i '1s/^/$c\n /' $i ; done

/$c\n/ is what is appended so you can do /LINECOUNT: $c\n/ , but keep the \n so the previous first line is not appended to but moved to the second line.

Upvotes: 1

NoChance
NoChance

Reputation: 5772

You can use the solution provided here - It works for one file, but you can place it in loop for the desired list of files.

Add text to top of file

Alternatively, you could write a program to do the task.

I suggest that you output the result to a separate folder and not overwrite the original files at first in case of a bug occurs, also test the approach for empty files or files where you don't have rights to access.

Upvotes: 0

Related Questions