I have a shell variable:
all_apk_file="a 1 2.apk x.apk y m.apk"
I want to replace the a 1 2.apk with TEST, using the command:
echo $all_apk_file | sed 's/(.*apk ){1}/TEST/g'
The .*apk means end with apk, {1} means only match one time, but it doesn’t work; I only got the original variable as output: a 1 2.apk x.apk y m.apk
Can anyone tell me why?
One part of the problem is that in regular
sed, the()and{}are ordinary characters in patterns until escaped with backslashes. Since there are no parentheses in the variable’s value, the regex never matches. With GNUsed, you can also enable extended regular expressions with the-rflag. If you fix that problem, you will then run into the problem that.*is greedy, and thegmodifier actually doesn’t change anything:It only stops there because there isn’t a space after
m.apkin the echoed value of the variable.The issue now is: what is it that you want replaced? It sounds like ‘everything up to and including the first occurrence of
apkat the end of a word. This is probably most easily done with trailing context or non-greedy matching as found in Perl regular expressions. If switching to Perl is an option, do so. If not, it is not trivial in normalsedregular expressions.This looks for anything without dots in it, followed by a blank, followed by no dots again, and
.apk; this means that the first dot allowed is the one in2.apk. It works for the sample data; it would not work if the variable contained:You’ll need to tune this to meet your requirements.