Linux/Unix tools for editing text files

Get the first or last lines of file

Commands head and tail prints on screen the first or last ten lines of given text file. The number of lines can be specified as an option. For example, the first line can be printed on screen with command:

head -1 tpc2345.tac

Output can be redirected to a new file, deleting any existing file:

head -1 tpc2345.tac > firstline.txt

, or appended to an existing (or new) file:

head -1 tpc2346.tac >> firstline.txt

Remove certain line(s) of a file

Specified line number can be easily deleted using sed. For example, line 3 can be deleted with command:

sed -i '3 d' tpc8765ap.bld

, or lines 2-4 could be deleted with command:

sed -i '2,4 d' tpc8765ap.bld

Remove comment line(s)

Data files often contain comment lines starting with '#'-character. If you need to make a new file without the comment lines, enter command:

sed '/^#/ d' < original.dat > new.dat

Replace a word with another word

All instances of a word can be replaced with another word also with sed. For example, to replace all instances of 'center' with 'centre' in file tpc.html, whether those are parts of words or separate words, enter command:

sed -e 's/center/centre/g' tpc.html

To replace only instances of entire words, we can use word boundary marker '\b', for example:

sed -e 's/\bcenter\b/centre/g' tpc.html

See also:

Tags: , , ,

Updated at: 2017-10-13
Created at: 2015-01-08
Written by: Vesa Oikonen