Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Find and replace using Parameter Expansion

I want to replace the input,

find_string: @include circle-progress(38px, 30px, #4eb630)

and output,

Output_string: @include circle-progress(38px, 30px)

using ${find_string//pattern/replacement_string} where pattern is , , #[A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9]?([A-Fa-f0-9]?([A-Fa-f0-9]?([A-Fa-f0-9])))' that I supply.

In the code below, simply the line matching pattern is printed i.e find_string, when I read lines of code from a file, whereas I want the output_string to be printed.

pattern="@include circle-progress\(([0-9]{1,3}px, ){2}#[A-Fa-f0-9]
{3,6}\)" /*regex the matches find_string*/

replace_glob=', #[A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9]?([A-Fa-f0-9]?([A-
Fa-f0-9]?([A-Fa-f0-9])))' /*glob pattern in the string to be replaced*/

while IFS='' read -r line || [[ -n "$line" ]]; do
   if [[ $line =~ $pattern ]] 
   then
      echo "${line//$replace_glob/}" 
   fi
done < "$1"
like image 330
HarshvardhanSharma Avatar asked Jul 17 '26 12:07

HarshvardhanSharma


1 Answers

The pattern in parameter expansion is not a regular expression but follows the same rules as glob pattern matching:

  • * : matches any character sequence
  • ? : matches any character
  • [..] : any character in set
  • [^..] or [!..] : any character not in set

with shell option : shopt -s extglob, some more features but less than regular expressions

  • @(..|..) : match any once
  • ?(..|..) : match any 0 or 1 times
  • *(..|..) : match any 0 or more times
  • !(..) : matches all except

However bash supports some basic regex, following should work:

string='@include circle-progress(38px, 30px, #4eb630)'
pattern='@include circle-progress\([ ]*[0-9]{1,3}px,[ ]*[0-9]{1,3}px(,[ ]*#[A-Fa-f0-9]{3,6}[ ]*)\)'
[[ $string =~ $pattern ]] && echo "${string//"${BASH_REMATCH[1]}"}"
like image 190
Nahuel Fouilleul Avatar answered Jul 20 '26 02:07

Nahuel Fouilleul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!