Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Leading Whitespace from File

My shell has a call to 'fortune' in my .login file, to provide me with a little message of the day. However, some of the fortunes begin with one leading whitespace line, some begin with two, and some don't have any leading whitespace lines at all. This bugs me.

I sat down to wrapper fortune with my own shell script, which would remove all the leading whitespace from the input, without destroying any formatting of the actual fortune, which may intentionally have lines of whitespace.

It doesn't appear to be an easy one-liner two-minute fix, and as I read(reed) through the man pages for sed and grep, I figured I'd ask our wonderful patrons here.

like image 679
Maarx Avatar asked Dec 20 '09 07:12

Maarx


People also ask

How do you remove leading spaces using sed?

Use sed 's/^ *//g', to remove the leading white spaces.

How do I remove white space in Unix?

s/[[:space:]]//g; – as before, the s command removes all whitespace from the text in the current pattern space.

Which of the following removes all leading whitespace?

Answer. lstrip() removes leading white-spaces, rstrip() removes trailing white-spaces and strip() removes leading and trailing white-spaces from a given string.


3 Answers

Using the same source as Dav:

# delete all leading blank lines at top of file
sed '/./,$!d'

Source: http://www.linuxhowtos.org/System/sedoneliner.htm?ref=news.rdf

Additionally, here's why this works:

The comma separates a "range" of operation. sed can accept regular expressions for range definitions, so /./ matches the first line with "anything" (.) on it and $ specifies the end of the file. Therefore,

  • /./,$ matches "the first not-blank line to the end of the file".
  • ! then inverts that selection, making it effectively "the blank lines at the top of the file".
  • d deletes those lines.
like image 139
Travis Bradshaw Avatar answered Oct 07 '22 15:10

Travis Bradshaw


# delete all leading blank lines at top of file
sed '/./,$!d'

Source: http://www.linuxhowtos.org/System/sedoneliner.htm?ref=news.rdf

Just pipe the output of fortune into it:

fortune | sed '/./,$!d'
like image 24
Amber Avatar answered Oct 07 '22 14:10

Amber


How about:

sed "s/^ *//" < fortunefile
like image 31
airportyh Avatar answered Oct 07 '22 16:10

airportyh