Thursday, March 17, 2022

[SOLVED] How to export each part of a line of text file to its own file?

Issue

I have these output values of an Arduino Sensor saved to text file like this

9 P2.5=195.60 P10=211.00
10 P2.5=195.70 P10=211.10
11 P2.5=195.70 P10=211.10
2295 P2.5=201.20 P10=218.20
2300 P2.5=201.40 P10=218.40
...
...

And I want to extract each column to its own text file.

Expected Output: 3 text Files Number.txt, P25.txt and P10.txt where

Number.txt contains

9
10 
11 
2295 
2300 

P25.txt contains

195.60 
195.70 
195.70 
201.20 
201.40 

and P10.txt contains

211.00
211.10
211.10
218.20
218.40

PS: the file has more than just 5 lines, so the code should be applied to every line.


Solution

Here is how you could do:

$ grep -Po '^[0-9.]+' data.txt > Number.txt
$ grep -Po '(?<=P2\.5=)[0-9.]+' data.txt > P25.txt
$ grep -Po '(?<=P10=)[0-9.]+' data.txt > P10.txt

  • ^: Assert position at the start of the line.
  • [0-9.]+ Matches either a digit or a dot, between one and unlimited times, as much as possible.
  • (?<=): Positive lookbehind.
  • P2\.5=: Matches P2.5=.
  • P10=: Matches P10=.

  • -o: Print only matching part.
  • -P: Perl style regex.


Answered By - Cubix48
Answer Checked By - Gilberto Lyons (WPSolving Admin)