Home > OS >  how to replace all quotes ' " in bash
how to replace all quotes ' " in bash

Time:04-21

I would like to remove simple ' and double quotes " with bash command, but I can't remove ' with bash command. I don't know what I'm doing wrong but this command gives me an error, anyone have any idea?

user_download_dir_folder=$(echo ${user_download_dir_folder} | sed "s/\"\'//g")

CodePudding user response:

Problem with sed "s/\"\'//g" is that you're trying to match a " followed by a '. You should put them in bracket expression or match either of the quotes.

Let's say this is your input:

user_download_dir_folder="abc\"1'23'foo\"bla"

echo "$user_download_dir_folder"

abc"1'23'foo"bla

You may use sed as this:

sed "s/[\"']//g" <<< "$user_download_dir_folder"

abc123foobla

Or in bash:

echo "${user_download_dir_folder//[\'\"]/}"

abc123foobla

CodePudding user response:

You can use string manipulation or tr:

user_download_dir_folder=$(tr -d \"\' <<< "$user_download_dir_folder")
# OR
user_download_dir_folder="${user_download_dir_folder//[\"\']/}"

See an online demo:

#!/bin/bash
user_download_dir_folder="12\"4'5"
user_download_dir_folder=$(tr -d \"\' <<< "$user_download_dir_folder")
echo "$user_download_dir_folder"
## => 1245

user_download_dir_folder="12\"4'5"
user_download_dir_folder="${user_download_dir_folder//[\"\']/}"
echo "$user_download_dir_folder"
## => 1245

CodePudding user response:

thanks a lot, it's working. finally i did this

user_download_dir_folder=$(echo ${user_download_dir_folder} | sed "s/\"//g" | sed "s/'//g") #remove ' and " 

but your solution is much better, and this solution is more elegant, and I didn't even think of it.

  • Related