Question

I have several lines looking like this:

4539(random number of spaces)07235001(random number of spaces)Aach(random number of spaces)Trier Saarburg

I want to separate it to 4 columns using C++ or linux. The output I want will look like this:

4539|07235001|Aach|Trier Saasburg

So I want to treat several spaces as the delimiter but not the single one.

(random number of spaces thankfully is always > 1)

Lines do not always consist of 4 columns and the space problem is not always at the last column.

Thanks in advance

Was it helpful?

Solution 2

You can use awk with regular expressions for this:

echo "4539     07235001      Aach    Trier Saarburg" | awk 'BEGIN { FS = "[ ]{2,}"  } { OFS = "|" };  {$1=$1; print $0 }' 

FS variable is used to set the field separator for each record and may contain any regular expression. OFS is the output equivalent of the FS variable.

OTHER TIPS

You should read each field individually. The last field can be read until a newline

character is received:  
std::string column1;
std::string column2;
std::string column3;
std::string column4;
while (input_file >> column1)
{
  input_file >> column2;
  input_file >> column3;
  getline(input_file, column4);
}

Another method is to read the entire line using getline and then fetch out the substring fields using std::string::find and std::string::substr.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top