MikeyCarter
MikeyCarter

Reputation: 11

Perl how do I add text to specifically second line of file?

Trying to do this sort of thing in perl:

sed '1 a<!-- $Header: $\n Purpose: system generated file -->' -i test.xml 

Add the header block and purpose to line #2 in the file for xml, shell scripts, etc...

Don't want to do this either:

`sed '1 a<!-- \$Header: \$\n Purpose: system generated file -->' -i test.xml`  

But realize it's an option if absolutely necessary.

Upvotes: 0

Views: 239

Answers (2)

ikegami
ikegami

Reputation: 385849

If you only pass one file, you can use the following:

perl -i -pe'
   $_ .= "<!-- \$Header: \$\n Purpose: system generated file -->\n" if $. == 1;
' test.xml

If you might pass multiple files, you'll need to add a line so that $. is reset at the end of each file.

perl -i -pe'
   $_ .= "<!-- \$Header: \$\n Purpose: system generated file -->\n" if $. == 1;
   close(ARGV) if eof;
' test*.xml

(Note: eof() means something different than just eof. how awful is that!)

I added line breaks for readability. The commands will work as is, but you can remove the line breaks if you so desire.

Upvotes: 3

user3849273
user3849273

Reputation: 271

Try this way:

perl -ple '++$i == 2 and $_ = "changed" # change $_ as you want' in.txt > out.txt

Upvotes: 0

Related Questions