Free Source Code and Program Tips
File processing — Remove the first column of each line
Question
I have a text file with a lot of lines, and in each line, there are several columns divided by space character, but the number of columns in each line varies. For example, here is a sample
——————– abc 123 234 456 bsc 3 5 7 9 10 123 yyt 23 ——————–
I want to get a new file based on the existing file, by removing the first column, here is the related output of above sample,
-------------------- 123 234 456 3 5 7 9 10 123 23 --------------------
Solution
perl is a bit faster than cut:
perl -pe ‘s/^[^ ]+\ *//’
Sed is a slower:
sed -e ‘s/^[^ ]\+\ *//’
Note: If you accept leading space characters, cut won’t work properly (it would treat the first field as being empty), but perl can work:
perl -pe ‘s/^\ *[^ ]+\ *//’
a little more robust program.
#include
#include
int main(int argc, char* argv[])
{
using std::string;
while (1)
{
string str_one_line;
if (!getline(std::cin, str_one_line))
break;
string::size_type pos = str_one_line.find_first_of(‘ ‘);
if (pos == string::npos)
{
std::cerr << "There is no space char in the string." << std::endl;
return 1;
}
pos = str_one_line.find_first_not_of(' ', pos + 1);
if (pos == string::npos)
{
std::cerr << "There is no char after space char." << std::endl;
return 1;
}
std::cout << str_one_line.substr(pos) << std::endl;
}
return 0;
}
| Print article | This entry was posted by hamo on November 24, 2006 at 12:27 am, and is filed under Win32/MFC. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |