I am attempting to make a code that searches on google from terminal by inserting thing into the link. Does anybody know how to replace spaces with pluses so that I can insert that into the link instead of the original search term. I am thinking of using things commands like sed, although I don't understand the formatting of sed.
I am currently using the below:
search() { read F1 a=$F1 b= c=$b$a echo OPENING: echo $c open $c } The problem is that this requires pluses instead of spaces. I need a way to replace spaces with pluses in the a variable.
113 Answers
To replace characters in a variable in the bash shell, you can use parameter expansion
Ex. to replace each space with a plus character
$ var='some string with spaces' $ echo "${var// /+}" some+string++++with+spaces or to replace sequences of spaces with a single plus (provided you have enabled extended globbing in the shell)
$ echo "${var//+( )/+}" some+string+with+spaces You can assign to a new variable newvar="${var//+( )/+}" or reassign to change the value of the variable directly i.e.
$ var='some string with spaces' $ echo "$var" some string with spaces $ $ var="${var//+( )/+}" $ echo "$var" some+string+with+spaces Here's an illustration of its use in the context described in your updated question:
Construct a minimal ~/.bash_profile
if [ -r $HOME/.profile ]; then . $HOME/.profile fi search() { read -p 'Please enter a search term: ' searchterm c="( )/+}" echo "OPENING: $c" } Then start a new login shell and test it
$ bash -l $ search Please enter a search term: ask ubuntu OPENING: $ 3You could use this command:
sed -i 's/ /+/g' filename 3I figured out how to do this and it works on my computer. Just use this code in your .bash_profile.
search() { clear echo Type in your search term: read F1 F=`echo "$F1" | sed "s/ /+/g"` echo Opening: "$F" open "$F" }