ramkrishna
ramkrishna

Reputation: 640

Getting error while replacing word using perl

I am writing a script for replacing 2 words from a text file. The script is

count=1
for f in *.pdf
do
    filename="$(basename $f)"
    filename="${filename%.*}"
    filename="${filename//_/ }"
    echo $filename
    echo $f

    perl -pe 's/intime_mean_pu.pdf/'$f'/' fig.tex > fig_$count.tex
    perl -pi 's/TitleFrame/'$filename'/' fig_$count.tex

    sed -i '/Pointer-rk/r fig_'$count'.tex' $1.tex
    count=$((count+1))
done

But the replacing of words using the second perl command is giving error:

Can't open perl script "s/TitleFrame/Masses1/": No such file or directory

Please suggest what I am doing wrong.

Upvotes: 2

Views: 95

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74645

You could change your script to something like this:

#!/bin/bash

for f in *.pdf; do
    filename=$(basename "$f" .pdf)
    filename=${filename//_/}

    perl -spe 's/intime_mean_pu.pdf/$a/;
    s/TitleFrame/$b/' < fig.tex -- -a="$f" -b="$filename" > "fig_$count.tex"

    sed -i "/Pointer-rk/r fig_$count.tex" "$1.tex"
    ((++count))
done

As well as some other minor changes to your script, I have made use of the -s switch to Perl, which means that you can pass arguments to the one-liner. The bash variables have been double quoted to avoid problems with spaces in filenames, etc.

Alternatively, you could do the whole thing in Perl:

#!/usr/bin/env perl

use strict;
use warnings;
use autodie;

use File::Basename;

my $file_arg = shift;
my $count = 1;

for my $f (glob "*.pdf") {
    my $name = fileparse($f, qq(.pdf));

    open my $in, "<", $file_arg;
    open my $out, ">", 'tmp';
    open my $fig, "<", 'fig.tex';    

    # copy up to match
    while (<$in>) {
        print $out $_;
        last if /Pointer-rk/;
    }

    # insert contents of figure (with substitutions)
    while (<$fig>) {
        s/intime_mean_pu.pdf/$f/;
        s/TitleFrame/$name/;
        print $out $_;
    }

    # copy rest of file
    print $out $_ while <$in>;

    rename 'tmp', $file_arg;
    ++$count;
}

Use the script like perl script.pl "$1.tex".

Upvotes: 2

marneborn
marneborn

Reputation: 699

You're missing the -e in the second perl call

Upvotes: 1

Related Questions