如何在同一文件中添加行数

时间:2014-12-24 20:58:59

标签: linux perl shell awk sed

如何在页脚中添加同一文件的总行数。

例如:

prabhat
prabhat1
prabhat3
prabhat4
prabhat5235
total 5 records are there in this file.

如上所述共有5行,所以在最后一行显示“此文件中共有5条记录”

4 个答案:

答案 0 :(得分:3)

在命令行中使用perl,使用-i,内联编辑,

perl -i -pe '$_ .= "total $. records are there in this file\n" if eof' file

答案 1 :(得分:2)

使用

尝试此操作
awk 'END{print "total "NR" records are there in this file"}' file | tee -a file

或使用

echo "total $(wc -l < file) records are there in this file" >> file

或使用

sed -i "\$atotal $(wc -l < file) records are there in this file" file

或使用

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

默认情况下,变量$^Iundef。如果您将其更改为其他内容,则会启用就地编辑文件。如果将字符串分配给$^I,则perl将通过创建名称由原始文件名加上分配给$^I的字符串组成的文件来备份原始文件。 perl的作用是:

  1. 创建一个新文件 - 其名称包含备份扩展名。
  2. 将原始文件的内容复制到新文件中。
  3. 打开原始文件进行书写,删除。
  4. 从新文件中读取。
  5. 将STDOUT重定向到原始文件,因此print()的内容将写入原始文件。

答案 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;是文件的路径