How to delimit the fields of a input file which has special characters?

Hi All, I am a newbie to Shell scripting. I have a requirement to Delimit the file fields of a Input file having special characters and spaces with ";".

Input File

 
----------------------------------
Server                    Port
----------------------------------
Local                      1001

-----------------------------------------
Name        Country        Count
-----------------------------------------
XXX          Bermuda        999

So my requirement is to get the output like,

Server;Port
Local;1001

Name;Country;Count
XXX;Bermuda;999

Kindly, Please help me to full-fill the requirement..

Thank you in advance

Welcome to the forum; and: thanks for intuitively using code tags correctly!

Any preferred tools? As you didn't specify what to do with the dash lines, nor with the empty lines (one is suppressed, one is retained), try (exploiting a few of awk 's internals and defaults):

awk '$1=$1' OFS=";" file
----------------------------------
Server;Port
----------------------------------
Local;1001
-----------------------------------------
Name;Country;Count
-----------------------------------------
XXX;Bermuda;999

EDIT: to remove the dash lines, expand like

awk '($1=$1) && 1-sub(/--*/,_)' OFS=";" file
Server;Port
Local;1001
Name;Country;Count
XXX;Bermuda;999
2 Likes

Thanks for the quick reply Rudic. I will try

---------- Post updated 03-02-17 at 06:01 PM ---------- Previous update was 03-01-17 at 09:03 PM ----------

When executed i am getting the below error

awk: syntax error near line 1
awk: bailing out near error 1

Assuming your OS - which you failed to mention - is SunOS or Solaris:

1 Like

Thanks Rudic.. It worked. Can you please help me if the country name is

Saudi Arabia

I am getting it output as

Saudi;Arabia

Sorry for changing the requirement. The output should be like

Server;Port;Name;Country;Count
Local;1001;XXX;South Africa;999

That dependes on if and how fields are separated uniquely. If there is any chance that fields are separated by just one single space, you're doomed. If there's ALWAYS multiple spaces separating fields, change the field separator to sth. like " +" .

1 Like