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 : |
You could use
Code:
sed -ne "s/^[^:]*\(.\{2\}\):.*$/\1/p" |
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
|
"^" 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. |
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' Code:
echo 'this is log file for deamon 1: which runs deamon program' |\ |
All times are GMT -5. The time now is 06:37 PM. |