Issue
I have a log file and i want to extract a line like this from it:
ERROR_RECHARGING! =====> THE CS IP = 10.10.10.10 and PASS = sdas3asdasd and SN = DFGT5334rFFDS IS RECHARGING NOW
After, i want to get only the IP value, Pass value and SN value and write it into another file in this mode :
ip;pass;sn
How can i do this in bash script with sed or awk?
Thanks
Solution
Sample data file:
$ cat csip.dat
ignore this line
ERROR_RECHARGING! =====> THE CS IP = 10.10.10.10 and PASS = sdas3asdasd and SN = DFGT5334rFFDS IS RECHARGING NOW
ignore this line
ERROR_RECHARGING! =====> THE CS IP = 85.13.125.158 and PASS = sdwXHWEFFsd and SN = 123abcd__243D IS RECHARGING NOW
ignore this line
The OPs sed
code (from comments) ...
$ sed 's/ERROR_RECHARGING! =====> THE CS IP = ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) and PASS = ([^ ]*) and SN = ([:alnum:]*) IS RECHARGING NOW/\1;\2;\3/g' csip.dat
... needs a few tweaks:
- add flags
-rn
to allow for extended regex support and to suppress automatic printing of input data to stdout - change
[:allnum:]
to[[:alnum:]]
- change the
/g
to/p
to change from replacement mode to print mode
The new sed
command looks like:
$ sed -rn 's/ERROR_RECHARGING! =====> THE CS IP = ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) and PASS = ([^ ]*) and SN = ([[:alnum:]]*) IS RECHARGING NOW/\1;\2;\3/p' csip.dat
10.10.10.10;sdas3asdasd;DFGT5334rFFDS
At this point we've accomplished what the OP wanted for the given set of data.
Assuming there may be more than one ERROR_RECHARGING
line to process, and assuming the 3rd field (sn
) may contain more than just alphanumerics (see 4th line is csip.date
- above), we can shorten the current sed
solution and generate 2 sets of output:
$ sed -rn 's/ERROR_RECHARGING! =====> THE CS IP = ([^ ]*) and PASS = ([^ ]*) and SN = ([^ ]*) .*/\1;\2;\3/p' csip.dat
10.10.10.10;sdas3asdasd;DFGT5334rFFDS
85.13.125.158;sdwXHWEFFsd;123abcd__243D
# or with some additional shorthand:
$ sed -rn 's/^ERROR_RECHARGING.* = ([^ ]*) .* = ([^ ]*) .* = ([^ ]*) .*/\1;\2;\3/p' csip.dat
10.10.10.10;sdas3asdasd;DFGT5334rFFDS
85.13.125.158;sdwXHWEFFsd;123abcd__243D
Where:
([^ ]*)
- match a pattern of (space) + (anything_other_than_space) + (space); eliminates lengthy[0-9]{1,3}
match for ip; also allows us to match onsn
that contains other non-alphanumerics.* =
- match anything up to a string of (space) +=
+ (space)
Answered By - markp-fuso