SED useful commands

Valic —  February 5, 2013 — Leave a comment

1. How to remove lines ending with ‘baddump’ from a text file:

You’ve got a file with a bunch of lines end with “baddump”  and you need those lines to be removed completely without leaving any blank lines behind? This is the command to do it:

sed -i '/baddump$/d' file

2. You have text files with tons of empty lines and you want to get rid of those in one second?

sed '/^$/d' file > new_file

You may have multiple html files to correct at the same time.You can do that with foreach command:

foreach file (*html)
sed '/^$/d' $file > new_files
mv new_files $file

3. Add character to the beginning of each line using sed:

In this example I will show you how to add a character to the beginning of each line using a sed command
Let’s create example file with some text:

nano file
this command
will add
at the
beginning of
each line

The command to do the job is:

sed 's/^/#/' file

cat file
#this command
#will add
#at the
#beginning of
#each line

4. Deleting lines starting with X character:

Do you have a file and you want to delete lines starting with certain characters?

sed '/^#/d' file

This command will delete all lines that starts with # character.

5. Removing a character using sed:
You  have a text file and you want to  remove the character “%” from the text file using sed ?

sed 's/%//' file > newfile

6. Deleting one or more lines from a file using sed:

Here is how to remove one or more lines from a file:

Remove the 4rd line:

sed '4d' file

Remove the last line:

sed '$d' file

Remove the interval between lines 1 and 20:

sed '1,20d' file

7. Search & Replace text in multiple files recursively using sed and find:

The following command will recursively find all files with extension .html starting with the current folder and replace xxx string with  zzz.

find . -name "*.html" -print | xargs sed -i 's/xxx/zzz/g'


Posts Twitter Facebook

Editor in Chief at Debian-Tutorials, Linux enthusiast.

No Comments

Be the first to start the conversation.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.