我有一個包含不同值的檔案:
30,-4,098511E-02
30,05,-4,098511E-02
41,9,15,54288
我需要從此檔案中洗掉值,但從不同的位置,例如:
30
30,05
41,9
我試圖sed洗掉最后一個值,但我的問題是當我遇到41,9,15,54288它不起作用時。知道是否有辦法嗎?
我試過這個
echo "30,-4,098511E-02" | sed 's/,.*/,/'
uj5u.com熱心網友回復:
使用sed
$ sed -E 's/(([0-9] ,?){1,2}),[0-9-].*/\1/' input_file
30
30,05
41,9
uj5u.com熱心網友回復:
我會用 perl 來做,像這樣:
#!/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;
我在我的代碼注釋中寫了我的正則運算式的解釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/505647.html
下一篇:基于索引的替換
