For Linux and Shell scripting.

Leave a comment

Remove everything in between two words from a file

You can use the script below if you want to remove lines/words in between two specific words. Run it like: “./scriptname filename” where filename is name of the file from which you want to remove.

You will have to edit following fields in the script:
“Remove from”
“Remove upto here”

The script will match first occurence of “Remove from” and will remove upto the first occurence of “Remove upto here”. But, it won’t stop there…….. it will search for the next occurance of “Remove from” and will delete everything upto next “Remove upto here”. The contents will be removed only if it matches both “Remove from” and “Remove upto here”

#! /bin/bash

function remove_it () {
sed -i ‘/Remove from/{
/Remove upto here/d
b loop
}’ $1

remove_it $1

Note: This script will rewrite the existing file. If you don’t want to rewrite the existing file, remove “-i” option from “sed”. And then redirect the output to a new file


How can I remove all line starting with hash (#)

To remove all lines starting with hast sign (#) from a file, try this:
sed /^#/d filename

The above command will remove all line starting with # from its output. If you want to write the output to another file, use o/p redirection >
sed /^#/d filename > newfile

But, if you want to over write the file with new o/p, use -i option with sed.
sed -i /^#/d filename