Home > OS >  Count file line along with file name in unix
Count file line along with file name in unix

Time:10-21

I have 3 files at temp dir as below :

test1.txt -- It has 4 lines
test2.txt -- It has 5 lines
test3.txt -- It has 6 lines

Need to count the lines in the file along with the name to a separate file (LIST.txt), like below

'test1.txt','4'
'test2.txt','5'
'test3.txt','6'

Code Tried :

FileDir=/temp/test*.txt

for file in ${FileDir}
do
filename=$(basename $file) & awk 'END {print NR-1}' ${file} >> /temp/LIST.txt
done

This is not giving me the name, it only gives me the line counts. Also, how to get the output of those 2 commands separated by ',' ?

CodePudding user response:

Perhaps this would suit?

FileDir=/temp/test*.txt
for file in ${FileDir}
do
  awk 'END{print FILENAME "," NR}' "$file"
done > LIST.txt
cat LIST.txt
/temp/test1.txt,4
/temp/test2.txt,5
/temp/test3.txt,6

Remove "/temp/" and include single quotes:

cd /temp
FileDir=test*.txt
for file in ${FileDir}
do
  awk 'END{q="\047"; print q FILENAME q "," q NR q}' "$file"
done > ../LIST.txt
cd ../
cat LIST.txt
'test1.txt','4'
'test2.txt','5'
'test3.txt','6'

An alternative approach:

FileDir=/temp/test*.txt
for file in ${FileDir}
do
  awk 'END{q="\047"; n = split(FILENAME, a, "/"); print q a[n] q "," q NR q}' "$file"
done > LIST.txt
cat LIST.txt
'test1.txt','4'
'test2.txt','5'
'test3.txt','6'
  • Related