[nylug-talk] need sed help

Eric Moore eemoore at fyndo.com
Tue Apr 3 12:40:53 EDT 2007


jh <jhlists at hirschman.net> writes:

> Ajai Khattri wrote:
>> On Tue, 3 Apr 2007, jh wrote:
>> 
>>> I'm trying to use sed to delete all the whitespace, up to the first 
>>> non-white character, on the first line of a file, and I can't make it 
>>> work. Can someone show me what will work?
>>>
>>> Tried this:
>>>
>>> sed -e 's/[\t]//1' problem.txt > out.txt
>>> sed -e 's/[\020]*//1' problem.txt > out.txt
>>> sed -e 's/[:space:]*//1' problem.txt > out.txt
>> 
>> 
>> http://sed.sourceforge.net/sedfaq3.html#s3.2
>> 
>> 
> Shouldn't this work?
>
> sed -e 's/^[\x20]*//1' problem.txt > out.txt

First odd, when you have a question like this, it helps to tell us
what doesn't work about it, like "it deletes all leading whitespace,
not just the first line".  This will help us diagnose your problem.

The numerical flags to the s command mean the n'th instance on a given
line (or more accurately, per pattern space, but that's almost always
a line).

So if we have this file:
nyarlothotep:~$ cat baz
   foo   bar   blech
   baz   quux

We can delete the first bit of whitespace with:

nyarlothotep:~$ sed -e 's/ \+//1' baz
foo   bar   blech
baz   quux

or the second with:

nyarlothotep:~$ sed -e 's/ \+//2' baz
   foobar   blech
   bazquux

So what your command: -e 's/^[:space]*//1' does is replace the first
instance of 0 or more space characters at the beginning of a line on
each line (which is somewhat redundant, because there can't be a
second instance of space at the beginning of a line).

What you really want is to use an address range:
nyarlothotep:~$ sed -e '1s/^ \+//' baz
foo   bar   blech
   baz   quux

-- 
Eric


More information about the nylug-talk mailing list