Question

Hello: I have a lot of files called test-MR3000-1.txt to test-MR4000-1.nt, where the number in the name changes by 100 (i.e. I have 11 files),

$ ls test-MR*
test-MR3000-1.nt  test-MR3300-1.nt  test-MR3600-1.nt  test-MR3900-1.nt
test-MR3100-1.nt  test-MR3400-1.nt  test-MR3700-1.nt  test-MR4000-1.nt
test-MR3200-1.nt  test-MR3500-1.nt  test-MR3800-1.nt

and also a file called resonancia.kumac which in a couple on lines contains the string XXXX.

$ head resonancia.kumac
close 0
hist/delete 0
vect/delete *
h/file 1 test-MRXXXX-1.nt
sigma MR=XXXX

I want to execute a bash file which substitutes the strig XXXX in a file by a set of numbers obtained from the command ls *MR* | cut -b 8-11.

I found a post in which there are some suggestions. I try my own code

for i in `ls *MR* | cut -b 8-11`; do
    sed -e "s/XXXX/$i/" resonancia.kumac >> proof.kumac
done

however, in the substitution the numbers are surrounded by sigle qoutes (e.g. '3000').

Q: What should I do to avoid the single quote in the set of numbers? Thank you.

Was it helpful?

Solution

This is a reproducer for the environment described:

for ((i=3000; i<=4000; i+=100)); do
  touch test-MR${i}-1.nt
done
cat >resonancia.kumac <<'EOF'
close 0
hist/delete 0
vect/delete *
h/file 1 test-MRXXXX-1.nt
sigma MR=XXXX
EOF

This is a script which will run inside that environment:

content="$(<resonancia.kumac)"
for f in *MR*; do
    substring=${f:7:3}
    echo "${content//XXXX/$substring}"
done >proof.kumac

...and the output looks like so:

close 0
hist/delete 0
vect/delete *
h/file 1 test-MR300-1.nt
sigma MR=300

There are no quotes anywhere in this output; the problem described is not reproduced.

OTHER TIPS

or if it could be perl:

#!/usr/bin/perl
@ls = glob('*MR*');

open (FILE, 'resonancia.kumac') || die("not good\n");

@cont = <FILE>;

$f = shift(@ls);
$f =~ /test-MR([0-9]*)-1\.nt/;
$nr = $1;

@out = ();
foreach $l (@cont){
    if($l =~ s/XXXX/$nr/){
        $f = shift(@ls);
        $f =~ /test-MR([0-9]*)-1\.nt/;
        $nr = $1;
    }
    push @out, $l;
}

close FILE;
open FILE, '>resonancia.kumac' || die("not good\n");
print FILE @out;

That would replace the first XXXX with the first filename, what seemed to be the question before change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top