I'm trying to write a bash script that would modify all occurrences of a certain string in a file.
I have a file with a bunch of text, in which urls occur. All urls are in the following format:http://example.com/JB007
(that's example.com/, followed by 4 OR 5 alphanumeric characters).
What I'd like do is append a string to all urls. I managed (with the help of user Dan Fego) to get this done with sed, but it only works by appending a static string.
What I'm looking for is a way to append a different string to each occurrence. Let's say I have a function generatestring
that echoes a different string every time. I'd like to append a different generated string to each url. http://example.com/JB007
would become http://example.com/JB007?GeneratedString1
and so on.
Does anyone know if this can be done? I've been told that perl is the way to go, but I have zero experience with perl. That's why I'm asking here.
Thanks in advance for any help.
If the URLs aren't alone in each line, you can do:
#!/usr/bin/perl
use strict;
use warnings;
sub generate {
my $i = shift;
return "GeneratedString$i";
}
my $i = 0;
while(my $line = <>) {
$line =~ s~(http://\S+)~$1 . "?" . &generate($i++)~eg;
print $line;
}
usage:
test.pl file_to__modify
output:
http://example.com/abc23?GeneratedString1
http://example.com/JB007?GeneratedString2