LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sed script (https://www.linuxquestions.org/questions/programming-9/sed-script-455570/)

cranium2004 06-17-2006 12:07 AM

sed script
 
how can i extract next 2 chars after some word from line from some given log file.
eg. say i have
this is log file for deamon 1: which runs deamon program
so what i want to extract 1 that mean i can say chars befors :

spirit receiver 06-17-2006 03:51 AM

You could use
Code:

sed -ne "s/^[^:]*\(.\{2\}\):.*$/\1/p"
It will look for the first colon in a line and discard everything but the preceding two characters.

cranium2004 06-17-2006 04:34 AM

thanks it worked. But can u explain it to me. also what i need to do same from doing it from last to fiest chars?? I mean your code searches for : from first char but same how can i do from last char

spirit receiver 06-17-2006 05:18 AM

"^" and "$" correspond to beginning/end of line. Then "[^:]*:" matches an arbitrary number of non-colon characters followed be a colon. We want to remember the two characters that precede the colon, so ":" is preceded by "\(.\{2\}\)". Then follows an arbitrary number of arbitrary characters, as indicated by ".*". Finally, "\1" replaces the whole line with the first content we remembered, i.e. the two characters preceding the colon. The command "p" tells sed to print the result.
If you want to look for the last colon instead of the first, it seems like "[^:]*" and ".*" should switch their roles somehow. Try it yourself.

archtoad6 06-21-2006 09:33 AM

Let me make 2 suggestions for improving the legibility of sed scripts. (So often the juxtapostion of all the '/' & '\' characters make them look like perl, or /dev/random, or Chuck Norris sparring w/ David Carradine.)

1. Utilize ',' or anything you like for the separator. sed uses the next character after 's' as the separator & it can be anything you like -- i.e. find legible. Thus, "sed 's, ... , ... ,' " works fine.

2. When using a lot of characters -- {}() -- that need escaping in sed to become metacharacters, use the "r" option to make them meta from the beginning.

3. It is customary to single quote sed's commands.

Thus, that nice little sed command becomes:
Code:

sed -rne 's,^[^:]*(.{2}):.*$,\1,p'
& can be tested like this:
Code:

echo 'this is log file for deamon 1: which runs deamon program'  |\
sed -rne 's,^[^:]*(.{2}):.*$,\1,p'



All times are GMT -5. The time now is 06:37 PM.