In my program, I would like to first get the user input, and insert a \
before each /
so I write this, but it doesn't work.
echo "input a website" read website sed '/\//i\/' $website
The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.
Bash allows you to perform pattern replacement using variable expansion like (${var/pattern/replacement}). And so, does sed like this (sed -e 's/pattern/replacement/'). However, there is more to sed than replacing patterns in text files.
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
Now that is more like it! You see how sed may be used in a bash script to print out any line in a file. In a command-line environment, sometimes the path to a solution yielding the least resistance is the sed way; otherwise, you end up doing more work than required in the first place.
We can use variables in sed using double quotes: sed -i "s/$var/r_str/g" file_name If you have a slash / in the variable then use different separator, like below:
The echo command output is piped into the sed command using the | (pipe) command – no source text file is specified as the input text is read from the piped input. The output of the sed command can be sent to a file by using the > command: If the output file name is the same as an existing file (including the input file), it will be overwritten.
Here is a list of the options available for sed, straight from the user manual: follow symlinks when processing in place; hard links will still be broken. edit files in place (makes backup if extension supplied). The default operation mode is to break symbolic and hard links.
Try this:
website=$(sed 's|/|\\/|g' <<< $website)
Bash actually supports this sort of replacement natively:
${parameter/pattern/string}
— replace the first match of pattern
with string
.${parameter//pattern/string}
— replace all matches of pattern
with string
.
Therefore you can do:
website=${website////\\/}
Explanation:
website=${website // / / \\/} ^ ^ ^ ^ | | | | | | | string, '\' needs to be backslashed | | delimiter | pattern replace globally
echo $website | sed 's/\//\\\//g'
or, for better readability:
echo $website | sed 's|/|\\/|g'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With