How to Add a Prefix to a Line in UNIX

The suite of tools installed in the Unix operating system for handing text manipulation can be enough to put even full blown programming languages to shame. With the awk text-processing utility, you can reformat entire documents in almost any conceivable way in a pain-free and automated fashion.

Instructions

    • 1

      Open a terminal. Most versions of Linux or Unix either open a terminal immediately when the operating system begins or have a terminal icon located on the task bar.

    • 2

      Type the following command:

      awk '{print "prefix "$0}'

      Nothing will appear to happen, but that is because the computer is waiting for you.

    • 3

      Type a line of text. For example, if you type:

      Hello.

      The awk program will immediately respond:

      prefix Hello.

      If you look at the command in awk in Step 2, perhaps you can work out why: awk is simply printing out the word "prefix" followed by the text given to it.

    • 4

      Use the following command to go through every line of a text file and add a prefix:

      cat textfilename | awk '{print "prefix "$0}'

      This prints the entire text file and "pipes" ( | ) it to awk.

      If the text file contains the lines:

      "Hello, how

      are you,

      my friend?"

      Then the result from awk will be:

      prefix Hello, how

      prefix are you

      prefix my friend?

Tips & Warnings

  • This just scratches the surface of awk. For example, the following command will print a line number before each line:

  • cat textfilename | awk '{orint NR " " $0}'

  • The result would be:

  • 1 Hello, how

  • 2 are you

  • 3 my friend?

  • You can read more about how to use awk at the GNU Awk User Guide (see reference).

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured