🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.unix.shell
Article #4101

Re: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ?

#4101
From: Ed Morton
Date: Sat, 22 Aug 2009 23:02
25 lines
2182 bytes
On Aug 22, 1:11 pm, bolega <gnuist...@gmail.com> wrote:
> sed/awk/perl:
>
> How to replace all spaces each with an underscore that occur before a
> specific string ?
>
> I really prefer a sed one liner.

Why?

> Example
> Input :  This is my book. It is too  thick to read. The author gets
> little royalty but the publisher makes a lot.
> Output: This_is_my_book._It_is_too__thick_to read. The author gets
> little royalty but the publisher makes a lot.
>
> We replaced all the spaces with underscores before the first occurence
> of the string "to ".

No, you replaced all ... the string "to " (note the space).

awk '{idx=index($0,"to "); tgt=substr($0,1,idx-1); gsub(/ /,"_",tgt);
print tgt substr($0,idx)}' file

   Ed.
Technical Details
Message-ID: <cde6b9df-5acc-41a7-acb3-a0f37348d644@z24g2000yqb.googlegroups.com>
Path: arc1-ca.pugleaf.net!g2news2.google.com!postnews.google.com!z24g2000yqb.googlegroups.com!not-for-mail
References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com>

Show Full Headers
Complete Article Headers
X-Google-Thread: bd748d9281,9ccd2e7066d84876
X-Google-Attributes: gidbd748d9281,public,usenet
X-Google-NewGroupId: yes
X-Google-Language: ENGLISH,ASCII
Path: arc1-ca.pugleaf.net!g2news2.google.com!postnews.google.com!z24g2000yqb.googlegroups.com!not-for-mail
From: Ed Morton <mortonspam@gmail.com>
Newsgroups: comp.unix.shell,gnu.emacs.help,comp.lang.python,comp.lang.lisp,comp.lang.scheme
Subject: Re: sed/awk/perl: How to replace all spaces each with an underscore 
 that occur before a specific string ?
Date: Sat, 22 Aug 2009 16:02:27 -0700 (PDT)
Organization: http://groups.google.com
Lines: 25
Message-ID: <cde6b9df-5acc-41a7-acb3-a0f37348d644@z24g2000yqb.googlegroups.com>
References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com>
NNTP-Posting-Host: 67.173.128.90
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
X-Trace: posting.google.com 1250982148 32572 127.0.0.1 (22 Aug 2009 23:02:28 GMT)
X-Complaints-To: groups-abuse@google.com
NNTP-Posting-Date: Sat, 22 Aug 2009 23:02:28 +0000 (UTC)
Complaints-To: groups-abuse@google.com
Injection-Info: z24g2000yqb.googlegroups.com; posting-host=67.173.128.90; 
 posting-account=rv7-7goAAAAyBCsUgaHaGs9haWRFGhT0
User-Agent: G2/1.0
X-HTTP-UserAgent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.2) 
 Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729),gzip(gfe),gzip(gfe)