Operating System - HP-UX
1753461 Members
4973 Online
108794 Solutions
New Discussion юеВ

Replace a Blank Char to ~ (tilde) Using 'sed' Command

 
SOLVED
Go to solution
Dewa Negara_4
Regular Advisor

Replace a Blank Char to ~ (tilde) Using 'sed' Command

Hi All,

I have an output below:
bdhp4126.na.pg.com ~17 Sep 2009~06:45:01~W~FILE

I want to add tilde (~) between date and month (char 29), and between month and year (char 33). So the output will be like below:
bdhp4126.na.pg.com ~17~Sep~2009~06:45:01~W~FILE

How can we do that using sed command? Please help. Thanks in advance.

Regards,
Santos
5 REPLIES 5
Hein van den Heuvel
Honored Contributor
Solution

Re: Replace a Blank Char to ~ (tilde) Using 'sed' Command

Just a regular expression...

Using perl:

$ cat x
bdhp4126.na.pg.com ~17 Sep 2009~06:45:01~W~FILE
$
$ perl -pe "s/(\d+) (\w+) (\d+)/\1~\2~\3/" x
bdhp4126.na.pg.com ~17~Sep~2009~06:45:01~W~FILE

So that looks for some numbers followed by a space stored in $1 (day)
followed by a word stored in $2 (month)
followed by a space and more numbers in $3 for the year.
Re-assemble with the tildes.

Hein.
Suraj K Sankari
Honored Contributor

Re: Replace a Blank Char to ~ (tilde) Using 'sed' Command

Hi,
awk '{ print $1" "$2"~"$3"~"$4 } outputfile

OR

awk '{
a=substr($0,1,22)
b=substr($0,24,3)
c=substr($0,28,20)
print a~b~c
}'outputfile

or

awk '{
print substr($0,1,22)"~"substr($0,24,3)"~"substr($0,28,20)
}'outputfile

Suraj
Suraj K Sankari
Honored Contributor

Re: Replace a Blank Char to ~ (tilde) Using 'sed' Command

Hi,
awk '{ print $1" "$2"~"$3"~"$4 }' outputfile

Suraj
James R. Ferguson
Acclaimed Contributor

Re: Replace a Blank Char to ~ (tilde) Using 'sed' Command

Hi:

Your requirement, based on the data presented, seems as simple as replacing blank characters with tildes. If that's truly the case, using 'sed' (as requested) this becomes:

# X="bdhp4126.na.pg.com ~17 Sep 2009~06:45:01~W~FILE"

# echo ${X}|sed -e 's/[ ]/~/g'

Regards!

...JRF...
Dewa Negara_4
Regular Advisor

Re: Replace a Blank Char to ~ (tilde) Using 'sed' Command

Hi All,

Got it. Resolved the issue using perl command as advised above. Thanks alot to you all for the great help.

Best Regards,
Santos