Saturday, May 17, 2008

How to indent lines in text files using sed, awk, perl

Suppose I have a text file named input.txt, and I want to indent each line in the file by 5 spaces.
$ cat input.txt
12
34
56
78


The following are different ways to do the same thing:
  • sed
    $ sed  's/^/     /'  input.txt
    12
    34
    56
    78

    s/^/ / searches for the beginning of a line (^), and "replaces" that with 5 spaces.

  • awk
    $ awk  '{ print "     " $0 }'  input.txt
    12
    34
    56
    78


  • perl
    $ perl -pe  's/^/     /' input.txt
    12
    34
    56
    78

To indent a range of lines, say lines 1 to 3, inclusive:
  • sed
    $ sed  '1,3s/^/     /' input.txt
    12
    34
    56
    78

    Note that the comma specifies a range (from the line before the comma to the line after).

  • awk
    $  awk  'NR==1,NR==3 {$0 = "     "$0} {print }' input.txt
    12
    34
    56
    78

    An awk program consists of condition/action pairs. The first pair has the condition "if NR (current line number) is from 1 to 3", and the action is to append 5 spaces to $0 (the current line). The second pair has a null condition which means it applies to every line, and the action is just to print the line.

  • perl
    $ perl  -pe '$_ = "     " . $_ if  1 <= $. and $. <=3' input.txt
    12
    34
    56
    78
    $. is the current input line number. $_ is the current line. . (dot) is the concatenate operator.

Click here for another post on sed tricks.

StumbleUpon Toolbar

No comments: