3. Processing files (write)

3.1 Create

You can process a file as described in the previous chapter. In this chapter you learn how to modify each line and how to save the results. There are two options:

  1. write the results to an other file via I/O redirection
  2. write the results into the current file via command switch -i (inline editing)
Study Chapter 2 for background information on processing files.

For demonstration purposes, we create a text file with some content.

This file name_age_1.txt contains four lines (format is name:age)

sebastian:41
daniel:39
florence:37
hannah:8

3.2 I/O redirection

Let's title case each line (record) of the inputfile name_age_1.txt and write all results to a second file output.txt.

$ perl -p -e '$_ = ucfirst($_);' < name_age_1.txt > output.txt
The contents of output.txt is:

Sebastian:41
Daniel:39
Florence:37
Hannah:8

3.3 Inline editing

The file name_age_1.txt contains four lines (format is name:age)

sebastian:41
daniel:39
florence:37
hannah:8


Again, let's title case each line (record) and write all results to the current file. The command switch for inline editing is -i.

$ perl -i -p -e '$_ = ucfirst($_);' name_age_1.txt
The contents of name_age_1.txt is now:

Sebastian:41
Daniel:39
Florence:37
Hannah:8
3.3.1 Backup original file
If you want to have a copy of the original before changing the original file, add .bak to the -i switch:

$ perl -i.bak -p -e '$_ = ucfirst($_);' name_age_1.txt
The file name_age_1.txt.bak is created first.

To place a backup into a subdirectory, you've first to create it. This is possible in a separate perl command, but you could use also the BEGIN block and then extend the -i switch with -i'subdirname/*':

$ perl -i'backups/*' -p -e 'BEGIN{mkdir("backups") if ! (-d "backups")} $_ = ucfirst($_);' name_age_1.txt

3.4 Remove empty lines

If App::pl is installed, write (after adding some empty lines in name_age_1.txt):

$ pl -Pi '/\S/' name_age_1.txt;