Operating System - Linux
1830165 Members
2355 Online
109999 Solutions
New Discussion

Re: sed and replace character

 
k_tohamy
New Member

sed and replace character

hi all
i have problem with sed command to replace space with _.

i have file formated as follow:

f_name = [kamal ahmed kamal] job = [sysadmin]
address = [30 A anything Street] ....etc
i want to replace only spaces between [ ].
so the file become:

f_name = [kamal_ahmed_kamal] job = [sysadmin]
address = [30_A_anything Street] ....etc

can any one help me ?
many thanks

kamal
3 REPLIES 3
spex
Honored Contributor

Re: sed and replace character

Hello kamal,

$ cat tr_sp.pl
#!/usr/bin/perl -wn
foreach $byte (split //,$_)
{
$byte =~ /\[/ and $br=1;
$byte =~ /\]/ and $br=0;
$br and $byte =~ s/ /_/;
print $byte;
}

$ cat recs
f_name = [kamal ahmed kamal] job = [sysadmin]
address = [30 A anything Street] ....etc

$ perl tr_sp.pl recs
f_name = [kamal_ahmed_kamal] job = [sysadmin]
address = [30_A_anything_Street] ....etc

PCS
Hein van den Heuvel
Honored Contributor

Re: sed and replace character

This ugly piece of perl seems to do it in one line.
I'm sure it can be writting better, but here it goes...

perl -pe '1 while (s/(\[\S*?)\s([^\[]+\])/\1_\2/)' x

Using s/x/y/g did only replace one space.

The while forces the repeated attempts.

(\[\S*?) looks for, and remembers in \1 an opening box and any number of non-whitespace

\s followed by whitespace

([^\[]+\]) followed by any number non-open-box, followed by a closing box, which is all remembered in \2.

Just using [^x]+ but the x is a [ and needs to be escaped giving [^\[]+

Replace the lot by \1, an _ and \2.

fwiw,
Hein.
MurugesanGCT
Advisor

Re: sed and replace character

With sed command use

sed 's/ /_/g;s/_=_/ = /g;s/\]_/\] /g' input_file

OUTPUT:
f_name = [kamal_ahmed_kamal] job = [sysadmin]
address = [30_A_anything_Street]
http://www.geocities.com/mukeshgct/