Reputation: 301
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://goo.gl/abc23
(that's goo.gl/, followed by 4 OR 5 alphanumeric characters).
What I'd like do is append a string to all urls. http://goo.gl/abc23
would become http://goo.gl/abc23?AString
, http://goo.gl/JB007
would become http://goo.gl/JB007?AString
and so on.
I've been trying this for the past 3 hours and got nowhere. I'm sure it's not very hard.
I've tried with sed (search and replace) and regex, but I don't know how to just append to a string, NOT replace it. I'm not very good with bash or regex.
Can anyone help me? Any help would be greatly appreciated.
Upvotes: 3
Views: 476
Reputation: 242038
You can use sed
to replace the end of string ($
):
sed 's/$/?AString/' input.txt
Upvotes: 0
Reputation: 14014
With sed
, your methodology would be to "replace the current string with the current string plus another one." So, if you had some regex to match all of your URLs (since I don't want to write one on the fly):
sed 's/myregex/&?AString/g' myfile.txt
You'd have your entire regex in place of myregex
. The &
character puts the entire matched string on the right side, and the rest of the right-hand part of the substitution adds ?AString
. The g
at the end tells sed
to substitute all instances on a line, rather than just the first.
Upvotes: 4
Reputation: 91498
A perl way to do it, assuming URLs end with a space:
perl -pne 's#(http://\S+)#$1?AString#g' input_file
Upvotes: 0