如何在页脚中添加同一文件的总行数。
例如:
prabhat
prabhat1
prabhat3
prabhat4
prabhat5235
total 5 records are there in this file.
如上所述共有5行,所以在最后一行显示“此文件中共有5条记录”
答案 0 :(得分:3)
在命令行中使用perl,使用-i
,内联编辑,
perl -i -pe '$_ .= "total $. records are there in this file\n" if eof' file
答案 1 :(得分:2)
使用awk:
尝试此操作awk 'END{print "total "NR" records are there in this file"}' file | tee -a file
或使用bash:
echo "total $(wc -l < file) records are there in this file" >> file
或使用sed:
sed -i "\$atotal $(wc -l < file) records are there in this file" file
或使用ed:
ed -s file <<!
$ a
total $(wc -l < file) records are there in this file
.
w
q
!
ex -s file << END_EX_COMMANDS
a
total $(wc -l < file) records are there in this file
.
w!
q
END_EX_COMMANDS
答案 2 :(得分:0)
use strict;
use warnings;
use 5.016;
{
local $^I = ".bak"; #Enables in place editing of files when reading files using the
#diamond operator(<>), which is the file input operator with no file handle specified.
#Original file saved with .bak extension.
local @ARGV = 'your_file.txt'; #The diamond operator(<>) reads from the file names in @ARGV.
while (my $line = <>) {
if (eof) { #then you've read the last line.
$line =~ s/\n/$.\n/; #When reading a file, $. is assigned the current line number
}
print $line;
}
}
your_file.txt:
one
two
three
four
five
程序输出:
one
two
three
four
five5
默认情况下,变量$^I
为undef
。如果您将其更改为其他内容,则会启用就地编辑文件。如果将字符串分配给$^I
,则perl将通过创建名称由原始文件名加上分配给$^I
的字符串组成的文件来备份原始文件。 perl的作用是:
答案 3 :(得分:0)
您也可以尝试
命令行
echo "total $(grep -c ^ <file_path>) records are there in this file" >> <file_path>
另一种方式
echo "total $(cat <file_path> |wc -l) records are there in this file" >> <file_path>
&LT; file_path&gt;是文件的路径