Perl and Map Line Insertion
Perl’s map function is quite powerful and even its simplest usage is fascinating. Once I have read about it I came up with a handy solution – how to insert text at the beginning of every line.
This can be done with just 1 line in perl:
print map { “YOUR TEXT $_” } (<>);
In case something is unclear explanation follows:
YOUR TEXT will be the text printed at the beginning of every line.
Perl’s default variable $_ represents the original line, in our case from a text file.
(<>) – the diamond operation assumes you will be reading a file.
So a sample, minimal perl, Linux usage will be:
$perl -e ‘print map { “YOUR TEXT $_” } (<>)’ OLD_FILE.txt > NEW_FILE.txt
This will insert YOUR_TEXT at the beginning of each line from the OLD_FILE.txt and save it all to NEW_FILE.txt.