Ubuntu: How to add a Suffix (or Prefix) to a Line of Text in a Text File using AWK CodeUnit 18 JUN 2012

If you are looking for a top notch tool to carry out quick text manipulations on text files under Ubuntu terminal, you could probably do no better than by looking up AWK (or I suppose SED if you are so inclined).

Anyway, back to AWK. The AWK utility is a data extraction and reporting tool that uses a data-driven scripting language consisting of a set of actions to be taken against textual data (either in files or data streams) for the purpose of producing formatted reports. The language used by awk extensively uses the string datatype, associative arrays (that is, arrays indexed by key strings), and regular expressions.

AWK was created at Bell Labs in the 1970s, and its name is derived from the family names of its authors – Alfred Aho, Peter Weinberger, and Brian Kernighan. ‘awk’, when written in all lowercase letters, refers to the Unix or Plan 9 program that runs other programs written in the AWK programming language.

Okay, now that we have some history, lets see just how easy it is to add either a prefix or suffix to each line contained in our text file using awk:

#add a prefix to each line in the text file
awk '{ printf("myprefix %sn", $l);}' sample-text-file.txt

#add a suffix to each line in the text file
awk '{ printf("%s mysuffixn", $l);}' sample-text-file.txt

#add both a prefix and a suffix to each line in the text file
awk '{ printf("myprefix %s mysuffixn", $l);}' sample-text-file.txt

The first example will result in each line in the sample text file being prepended with the word ‘myprefix’. The second example will result in each line in the sample text file being appended with the work ‘mysuffix’. I doubt that at this stage I still need to spell out what the third example does!

If you wish to save these changes to a text file, using the standard IO redirect functionality, i.e. the > sign:

#save output to a file
awk '{ printf("myprefix %s mysuffixn", $l);}' sample-text-file.txt > altered-text-file.txt

(Note that you shouldn’t direct the output at the input file as you’ll seriously screw things up. Rather save to a new file instead).

Nifty.

Related Link: http://en.wikipedia.org/wiki/AWK

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.