Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

bash - Using a .csv file as a data pool for the sed function

I have a large amount of text that I would like to use sed on to do a mass substitution using a .csv file as the data pool for sed to reference. For instance if I wanted to create a .csv file that looks like:

bird,snake
tree,bush
river,stream

Then I want use sed to search my text for column 1 strings and replace with column 2 values. Is this something that would best be done with a bash script calling sed, or would I have more success using a Perl script?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Perl. Read the CSV file into a hash, build a regular expression from the hash keys, and do a global subtitution on the text using the hash to translate.

It looks like this

use strict;
use warnings;
use 5.010;
use autodie;

my $str = <<'__END_TEXT__';
The ripple-necked bird sang melodies by the curling river while
the hooded tiger glowered in the tree beneath her, just out of reach.
__END_TEXT__

open my $fh, '<', 'words.csv';
my %patterns = map {
   chomp;
   split /,/, $_, 2;
} <$fh>;

my $re = join '|', sort { length $b <=> length $a } keys %patterns;

$str =~ s/($re)/$patterns{$1}/g;

say $str;

output

The ripple-necked snake sang melodies by the curling stream while
the hooded tiger glowered in the bush beneath her, just out of reach.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...