在文件中每行的开头和中间添加字符串

时间:2015-12-11 04:03:12

标签: perl

我的文件包含以下内容:

React.render()

我需要将其转换为以下格式......

ii, aa;



    jj, bb; // this is a comment

    hh;
 kk; /*this is comment*/

我有perl脚本的这部分

console.log(ii, aa);
console.log(jj, bb);
console.log(hh);
console.log(kk);

结果

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   chop;
   s/^[^\r\n].*;*$/console.log($_);/g; # do the replacement
   print $_, "\n"; # print to the modified file
}

根据解释改变这个有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

如果你可以依赖于每一个重要的输入行都有一个语句(和一个分号),那么这是编写解决方案的一种整洁方式

use strict;
use warnings 'all';

while ( <DATA> ) {
    next unless s/;.*/);/;
    s/^\s*/console.log(/;
    print;
}

__DATA__
ii, aa;



    jj, bb; // this is a comment

    hh;
 kk; /*this is comment*/

输出

console.log(ii, aa);
console.log(jj, bb);
console.log(hh);
console.log(kk);

答案 1 :(得分:1)

您可以尝试以下方式:

while (<>) {
    chop;
    next if /^\s*$/; # skip empty lines
    s/^\s+//; # remove leading whitespace
    s/;.*$//; # remove semi-colon and any comments;
    print "console.log($_);\n"; # print to the modified file
}
相关问题