sed tip: Remove / Delete All Leading Blank Spaces / Tabs ( whitespace ) From Each Line
The sed (Stream Editor) is very powerful tool. Each line of input is copied into a pattern space. You can run editing commands on each input line to delete or change the input. For example, delete lines containing word DVD, enter:
cat input.txt | sed '/DVD/d'
To Print the lines between each pair of words pen and pencil, inclusive, enter:
$ cat input.txt sed -e '/^PEN/,/^PENCIL/p'
To remove all blank lines, enter:
$ cat /etc/rssh.conf | sed '/^$/d' > /tmp/output.file
sed is very handy tool for editing and deleting unwanted stuff. Following echo statements printed lots of whitespace from left side:
echo " This is a test"
Output:
This is a test
To remove all whitespace (including tabs) from left to first word, enter:
echo " This is a test" | sed -e 's/^[ \t]*//'
Output:
This is a test
Where,
- s/ : Substitute command ~ replacement for pattern (^[ \t]*) on each addressed line
- ^[ \t]* : Search pattern ( ^ - start of the line; [ \t]* match one or more blank spaces including tab)
- // : Replace (delete) all matched pattern
Following sample script reads some data from text file and generate a formatted output. It delete all leading whitespace from front of each line so that text get aligned to left:
#!/bin/bash FILE=url.dump.txt DOMAIN=yourdomain.com exec 3<&0 exec 0<$FILE while read line do url=$(echo "http://${DOMAIN}${line}") title="$(lynx -dump -source ${url} | grep '<title>' | awk -F '<title>' '{ print $2 }' | cut -d'<' -f1|sed 's/^[ \t]*//')" echo " <li>${title}</li> " done exec 0<&3
To delete trailing whitespace from end of each line, enter:
$ cat input.txt | sed 's/[ \t]*$//' > output.txt
Better remove all leading and trailing whitespace from end of each line:
$ cat input.txt | sed 's/^[ \t]*//;s/[ \t]*$//' > output.txt
Want to stay up to date with the latest Linux tips, news and announcements? Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
You may also be interested in other helpful articles:
- What is the difference between password and passphrase under OpenSSH with DSA / RAS public key authentication?
- Quick Tip: Postfix Flush the Mail Queue
- FreeBSD: Customize Home, Del, Insert keys for BASH shell
- How to: Linux / UNIX Delete or Remove Files With Inode Number
- Open or use MS Office Documents in Linux or FreeBSD
Discussion on This Article:
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: sed blank line, sed delete blank lines, sed delete empty lines, sed remove blank line, sed remove blank lines, sed remove empty lines, stream editor, whitespace



http://sed.sourceforge.net/sed1line.txt is a very handy document for sed too.
Thanks for sharing the link