Add space before and after

Posted on 2011-05-09
Last Modified: 2012-05-11

I have a file with words on each line



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


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
Question by:faithless1
    LVL 26

    Accepted Solution

    Here's a short script because I found it easier as a first pass...

    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

    Author Comment

    Amazing - Thank you very much!

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
    Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now