Manipulating Files Using Terminal Commands

back to tech articles
CentOS 6.4

Here’s a few very quick and basic commands to do things with files via the terminal. These can be vastly improved upon; please comment if you have better methods for this.

Basic commands

1
2
3
4
5
6
// view the first 25 lines in a file
$ head -25 filename.sql
// view the last 25 lines in a file
$ tail -25 filename.sql
// delete the first 25 lines using sed
$ sed -i '1,25d' filename.sql

Heads and Tails, get it? 😉 Clever, these ‘nix folks! These could also be complicated as follows (this becomes useful when we begin chaining commands together with the pipe | connector).

1
2
3
4
// view the first 25 lines in a file
$ cat filename.sql | head -25
// view the last 25 lines in a file
$ cat filename.sql | tail -25

Let’s copy sections of a HUGE file into a smaller file.

Add Complexity With Pipes

1
2
3
4
// create empty file new.sql and insert the first 25 lines of filename.sql into it
$ cat filename.sql | head -25 > new.sql
// append first 25 lines of filename.sql to existing data in new.sql
$ cat filename.sql | head -25 >> new.sql
1
2
3
4
// replace 'old' with 'new' in a file
$ sed 's/old/new/g' filename.sql
// string some commands together
$ cat filename.sql | head -25 | sed 's/old/new/g' > new.sql

This is just a quick brain-dump.

Leave a Reply

Your email address will not be published. Required fields are marked *