Search

Creating a template for text files with some default text

Very often while writing programs or text documents, we use a certain content in every file we write. For eg almost every "c" file has the following lines



To avoid typing this repeatedly we can create a template which we can use to intialize our file with the default text.

Here are a two ways we can do it using shell scripting.

1. Taking the same example of a "c" file as above we can create a script as below



In the above script the first set of echo commands are for the text we want our text file to have.

Let us call this script as template.sh

To this script we will pass the new file name which we want to create and use the "vi" editor to open it for editing.

To open a file by the name test having the required contents already entered i in it run the script as follows.



You should see a new file opened in the vi editor with the following contents.



2. The second way doing the same, especially when the text to be entered is more than a few lines we can create a file that has the required text and use the same to create the new file.

For eg:

Let us create a new file called "template" and put the required contetns into it

template:

Let us say the above file is saved at the location /home/user/template.

We can use this file as shown in the script below



save the script as template2.sh and execute it as follows



A new file by the name test should get created which has the contents of the file template in it.

Below is a script that combines the above two into one, and makes it more dynamic such that it is able to create any number of files whose names are passed on the command line .

template.sh:

To make this command work from any terminal you want, copy this script to /usr/bin as follows

Note: This will prompt for your password and you will be able to execute this only if you have root permissions.



If that is successful, you can call this command from any where in the system and create ths files with default text in it, all you have to do is modify the script with the text that you want.

2 comments:

  1. Hey it's a nice one.keep posting.

    ReplyDelete
  2. Thanks alot! This will help me alot for my domain managment, it will be so easy to automate everything for adding new domains to my current webserver and bind configuration.

    ReplyDelete