[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 258
  • Last Modified:

Add space before and after

Hello,

I have a file with words on each line

i.e.

store
went
why
in
a
why

I also have another file that's not properly formatted. (file2)

storewent
wentwhystore

I'm looking for a one liner which will take add a space before and after in file 2 based on input of words.

Thank you
0
faithless1
Asked:
faithless1
1 Solution
 
wilcoxonCommented:
Here's a short script because I found it easier as a first pass...

#!/usr/local/bin/perl
use strict;
use warnings;
use Tie::File;

my $in = shift || die "Usage: $0 word_file bad_format_file\n";
my $out = shift || die "Usage: $0 word_file bad_format_file\n";

open IN, $in or die "could not open $in: $!";
my $rx = join '|', map { chomp; $_ } <IN>;

tie my @out, 'Tie::File', $out or die "could not tie $out: $!";
foreach my $ln (@out) {
    $ln =~ s{($rx)}{$1 }g;
}

Open in new window


If you really want a one-line, here's the equivalent (using -i instead of Tie::File)...

perl -i -e 'open IN, "words.txt" or die $!; $rx = join "|", map { chomp; $_ } <IN>; while (<>) { s{($rx)}{$1 }g; print }' bad_format.txt
0
 
faithless1Author Commented:
Amazing - Thank you very much!
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now