Forums

Brackets and curly brackets keyboard issue

Hello there! Recently I experienced some problems while trying to type " [ ] " or " { } " in the bash shell. This was a very sad surprise for me. I'm learning python and I really like the concept of regular expressions, so when I discovered egrep I immediately recognized the potential. Too bad I couldn't use brackets!

So,because I'm trying to learn how to use the bash, I wrote a little bash script as a workaround. The idea is to use 4 "special pairs" of characters, and replacing them with the appropriate brackets using string replacements:

§- -§ = [ ]

§ § = { }

It's clunky, but it's the simplest solution that came into my mind. I would like to share the code with you, so maybe you can tell me what you think and perhaps suggest me some tips to improve it. Since I'm a noob with the bash, I'm afraid that there will be lots of bugs! Anyway, here is the code:

#!/bin/bash
# regrep 1.0
#
#by Ofione
#
#Since I can't use square and curly brackets, I will use these special pairs of characters:

#§- -§= [ ]

#§_ _§= { }

#These pairs will be replaced with the right bracket with string replacements and the result will be used as a pattern
#in egrep, with the chosen flag. The result is then piped to less.

#create the argument list

args=("$@")

pattern=${args[0]}

flag=${args[1]}

#replace the special pairs with the right brackets

left_bracket="["
right_bracket="]"
left_cBracket="{"
right_cBracket="}"

firstReplace=${pattern/"§-"/$left_bracket}
secondReplace=${firstReplace/"-§"/$right_bracket}
thirdReplace=${secondReplace/"§_"/$left_cBracket}
lastReplace=${thirdReplace/"_§"/$right_cBracket}

egrep $lastReplace $flag|less

For testing purposes, I created test.txt, with the following content:

In this file there are
a bunch of stringsddd
some of them will contain exactly three "d"
let's see if egrepddd matches them with regular expression syntax

The goal here is find and match lines that have exactly three d ("ddd") and print the line number. The syntax would normally be:

egrep "[d]{3}" -n

So, I would use regrep as this (I have it in .local/bin/ so I can use it wherever I am):

less test|regrep §-d-§§_3_§ -n

And this is the output:

2:a bunch of stringsddd
4:let's see if egrepddd matches them with regular expression syntax

As you can see, the correct lines are matched and the line number is printed, so I can pass flags also.

Phew! Sorry for the wall of text, I hope you can find this useful :)

Cool. Thanks for that. I hope others find it useful.