How to combine grep command and sed command on the same text file and get output to another file?
Your command gives no output because the second grep
command doesn't match anything:
grep -Eo "[0-9]{12}"
That looks for exactly 12 consecutive numbers but you never have 12 consecutive numbers because your first grep
only prints out the date and time, so the rest of the line is already lost.
If your input really is just the two lines you show, then all you need is to print the 1st, 2nd and 11th field on lines that have at least 11 fields:
$ awk 'NF>10{print $1,$2,$11}' file
2021-06-12 20:59:41.118 213550040214
If you have more lines and really need to match the specific date and time format, you can try this instead:
$ sed -En 's/([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}).*([0-9]{12}) .*/\1 \2/p' file
2021-06-12 20:59:41 213550040214
The -E
enables extended regular expressions which simplify the syntax here and the -n
tells sed
not to print anything by default. Then, the substitution operator (s/old/new/
) will try to match the formats you are looking for and capture them (the parentheses "capture" patterns) so we can replace everything with just the two matched sections (\1 \2
).
Note that this will find the last stretch of 12 numbers, so it will fail if you have more than one such set. We could give you a more specific solution but you would have to give us more details about your file, what is variable and what never changes.