ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
I have a file that has a list of entries in a column
x
z
z
z
x
y
z
The column can have any length and any number of any strings. I need to replace each unique string with a user defined number. I can filter the unique entries out using
I then want to ask the user 'what do you want to replace x with? what do you want to replace y with?' and so on. I then set up a loop to read each line in the file as a variable and loop over these and replace each one with the user input
Y=1
while [ $Y -le $Nspecies ]; do #Nspecies is 3 in this case
species=`grep "$Y" species.tmp | awk '{print $2}'` #pick species in turn
echo "Enter vibration amp. for species" $species #user defined replacement
read amp
sed s/"$species"/"$amp"/ speciesorder.txt >> $outfile #do switch replace
Y=$((Y+1))
done
This almost works, it loops over the species x,y,z and asks for input but it always overwrites x again and again and doesn't move onto the others. I think the problem lies in the sed substitution of a variable for a user defined variable.
I would really appreciate any mistakes you might have spotted or any other ways to do this you might think of.
#! /usr/bin/perl -w
use strict;
use vars qw($old $new $slurp);
open IN, "sort -u @ARGV|" or die "oops:$!";
{
local $/ = undef;
$slurp = <ARGV>;
}
foreach $old (<IN>) {
print "\nSpecify vibrational amplitude for species $old";
$new = <STDIN>;
$slurp =~ s/$old/$new/g;
}
open(INFO, ">replaced.txt");
print INFO $slurp;
close(INFO);
usage script.pl infile
outfile automatically becomes replaced.txt but that can easily be fixed.
Thanks Billy. I might look into perl a bit more now.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.