开发者

string pattern replacement in bash

开发者 https://www.devze.com 2023-01-30 23:47 出处:网络
Using bash, I have a string: str=\'a $s\' echo ${str/\\$/\\$a} # a $as str=\'a $1\' echo ${str/\\$/\\$a} # a $a1

Using bash, I have a string:

str='a $s'
echo ${str/\$/\$a}
# a $as
str='a $1'
echo ${str/\$/\$a}
# a $a1

How modify pattern that replacement performs only if word开发者_开发技巧 starts with a letter?

I want

str='a $s'
echo ${str/??/??}
# a $as
str='a $1'
echo ${str/??/??}
# a $1


This would have been trivial if the regex support in Bash allowed lookahead. The solution would then simply be ${str/\$(?=[a-zA-Z])/\$a}. Unfortunately, that is not the case.

You can still do it if you don't might using sed.

str='a $s'
echo $str | sed 's/\$\([a-zA-Z]\)/\$a\1/g' # gives you a $as

str='a $1'
echo $str | sed 's/\$\([a-zA-Z]\)/\$a\1/g' # gives you a $1

\$\([a-zA-Z]\) matches $ followed by an alphabet and store the alphabet. If a match is found, it is replaced with $a followed by the stored alphabet (\1). For more details, see this tutorial.

The trailing g means it will match all occurrences in the string. Remove that if you only want to only replace the first occurrence.


You can use an IF to check if any any letter follows the dollar sign and in case do the replacement:

if [[ "$str" =~ \$[[:alpha:]] ]]; then 
    echo ${str/$/\$a}; 
else 
    echo $str; 
fi


Demonstration:

for str in 'a $1' 'a $s'
do
    [[ $str =~ \$([[:alpha:]]) ]]
    echo ${str/\$/\$${BASH_REMATCH[1]:+a}}
done

Result:

a $1
a $as
0

精彩评论

暂无评论...
验证码 换一张
取 消