LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   text processing (https://www.linuxquestions.org/questions/linux-general-1/text-processing-45917/)

Gantrep 02-17-2003 09:27 PM

text processing
 
How would I go about removing the first 7 characters and the last eight characters of every line of a file (or text stream). I've read man pages for cut, head, tail, and none seem to do exactly what I want. The stuff in between those characters I want removed is of variable length, otherwise I think cut, head, tail would do the job.

Thanks in advance.

crabboy 02-17-2003 09:38 PM

Write a C program. It would be just a couple of lines.

Wolven 02-17-2003 09:57 PM

You would use sed. It's a "Stream EDitor."

Here is an example that would cut away the first and last 3 lines of text. If you can't do it, I'll write you the script that will rip the letters you want.



sed -ne '1{n;n;n;N;N;}' -e '$d;N;P;D'



Here's a link to a sed tutorial for you. It has links to other tutorials as well.

http://www.selectorweb.com/sed_tutorial.html

Edit:
One more thing. If the words are all exactly the same, for example, if you had the numbers 1234567 at the beginning and end of every file, you could just run


sed s/"1234567"//g FILENAME



and it would replace "1234567" with whatever is between the slashes. In this case, nothing is between the slashes, so it replaces it with nothing. The same as deleting it.

crabboy 02-17-2003 10:15 PM

Here is quick and dirty:
Didn't know if you wanted to count newlines??
Make sure you test it, i'm sure it has bugs.

Code:

#include <stdio.h>
#include <unistd.h>

#define BUFLEN 2048
#define STRIPBEG 7
#define STRIPEND 9  /* Adding one additional for newline */

main()
{
  char szInString[ BUFLEN  + 1];
  int iStrLen = 0;
  int iNewEnd = 0;

  while ( fgets( szInString, BUFLEN, stdin  ) != NULL )
  {
      iStrLen = strlen( szInString );
      if ( iStrLen > ( STRIPBEG + STRIPEND ))
      {
        iNewEnd = iStrLen - STRIPEND;
        szInString[iNewEnd] = (char)NULL;
        printf ("%s\n", szInString + STRIPBEG );
      }
  }

}


Gantrep 02-17-2003 10:37 PM

Hey thanks folks. Sed was what I was looking for I guess.

I've actually had some C++ experience, but I was trying to stay away from that. I may use your code anyway though crabboy. I am grateful that you posted it.


All times are GMT -5. The time now is 02:12 AM.