在 unix 中计算文件行和文件名

Count file line along with file name in unix

我在临时目录中有 3 个文件,如下所示:

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

需要将文件中的行数连同名称一起计算到一个单独的文件中 (LIST.txt),如下所示

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

尝试过的代码:

FileDir=/temp/test*.txt

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

这不是给我名字,它只是给我行数。 另外,如何获取以“,”分隔的这 2 个命令的输出?

也许这会合适?

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

删除“/temp/”并包含单引号:

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

另一种方法:

FileDir=/temp/test*.txt
for file in ${FileDir}
do
  awk 'END{q="7"; 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'