0

Still working on my sed usage, but here's the very simple run down:

I would like to replace an integer within a string and do so x number of times. A user will input a string with "&Page=#&PageSize=#" such as the one below and from there the integer must be changed and on each change it must be appended to a file.

20601300929&Page=1&PageSize=96

What needs to be replaced is very simply "Page=1" to "Page=2". I could build a counter that increases the integer, but what I need is to automate the process of identifying and replacing the integer and then appending each counted change into a text file.

The expected result would be a simple file containing:

20601300929&Page=1&PageSize=96
20601300929&Page=2&PageSize=96
20601300929&Page=3&PageSize=96
... Until 100
2
  • 2
    Does it have to be sed? The problem is sed cannot count; bash and awk can. Apr 30, 2020 at 21:38
  • Ah thank you, of course yes it can be more, I was simply in the brain space of sed for the text replacement.
    – Tmanok
    May 1, 2020 at 1:00

2 Answers 2

3

You can do it with awk:

echo '20601300929&Page=1&PageSize=96' |
awk -F "Page=" '
    {
        split($2,a,"&")
        for (i=int(a[1]);i<=100;i++){
            print $1 FS a[1]++ "&" a[2]
        }
    }'

The field separator is set to Page=, so that field $2 is 1&PageSize=96 in our example.

The split bit splits that second field based on & and put in a[1] the number and in a[2] the rest of the string (PageSize=96).

Finally, in the print statement all is glued together.

4
  • Wow that worked like a treat! Thank you very much!!
    – Tmanok
    May 1, 2020 at 0:51
  • Question: While implementing in a script I have the original string pasted after the full executable, making it $1. So I've replaced "echo 'string' |" with "echo '$1' |" and it stopped working altogether. After using no single quotes around $1, I found that it forgot to add the end bit (&PageSize=96) back to the string.... What am I missing? Thx
    – Tmanok
    May 1, 2020 at 1:38
  • @Tmanok You're welcome, glad to help. You should double quote: "$1". When running the script, you should also double-quote the argument: ./script "20601300929&Page=1&PageSize=96".
    – Quasímodo
    May 1, 2020 at 10:13
  • Ah excellent thank you! Yes bash was getting rather confused when insert the strings because of how it handles ampersand and other characters.
    – Tmanok
    May 1, 2020 at 17:47
1

Maybe bash

num=96
counter=1
limit=100
var='20601300929&Page=#&PageSize=#'

while ((counter<=limit)); do
  if [[ $var =~ ([^\&]+)(\&[^\&]+)(.+) ]]; then
    printf '%s\n' "${BASH_REMATCH[1]}${BASH_REMATCH[2]/\#/$((counter++))}${BASH_REMATCH[3]/\#/$num}"
  fi
done


1
  • 1
    This one worked very well when using the "#" where the variables are, thank you very much I love the pure bash!
    – Tmanok
    May 1, 2020 at 0:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .