How to remove values from text file from different position

Viewed 31

I have a file containing different values:

30,-4,098511E-02
30,05,-4,098511E-02
41,9,15,54288

I need to remove values from this file but from different position, for example:

30
30,05
41,9

I tried to do it with sed to remove the last value but my problem is when I encounter the 41,9,15,54288 it does not work. Any idea if there is a way to do it?

I tried this

echo "30,-4,098511E-02" | sed 's/,.*/,/'
2 Answers

Using sed

$ sed -E 's/(([0-9]+,?){1,2}),[0-9-].*/\1/' input_file
30
30,05
41,9

I would do it using perl, like this:

#!/usr/bin/perl

use strict;
use warnings;

# my $inputPath  = '/Users/myuser/Desktop/inputs/a.txt';
# my $outputPath = '/Users/myuser/Desktop/outputs/a_result.txt';

if ($inputPath eq "") {
  print "Enter the full path of your input file: ";
  $inputPath = <STDIN>;
  chomp $inputPath;
}
if ($outputPath eq "") {
  print "Enter the full path of your input file: ";
  $outputPath = <STDIN>;
  chomp $outputPath;
}

open my $info, $inputPath or die "Could not open $inputPath: $!";

open FH, '>', $outputPath or die "Could not open $outputPath : $!";

while( my $line = <$info>)  {   
  chomp $line;
  # print "line read: $line\n";    

  # 30,05,-4,098511E-02
  # [0-9]: begins with a digit
  # 3
  # [0-9]+: begins with two digits
  # 30
  # [0-9]+: begins with two digits and a comma
  # [0-9]+?: begins with two digits and has or has not a comma
  # [0-9]+?: begins with two digits and has or has not a comma
  # 30,
  # {1,2}: one or two times
  # 30,05,
  # [0-9-]: anything that is a digit, or a dash
  # 30,05,-
  # [0-9-].: anything that is a digit, or a dash and any character after that
  # 30,05,-4
  # *: Matches anything in the place of the *, or a "greedy" match (e.g. ab*c    returns abc, abbcc, abcdc)
  # 30,05,-4,098511E-02
  if ($line =~ m{((([0-9]+,?){1,2}),[0-9-].*)}) {
    # print "becomes: $1\n";
    print FH "$1\n"; # Print to the file
  } else {
    print "not found!\n";
  }
}

close $info;

I wrote the explanations of my regex in the comments of my code.

Related