-2

I'm trying to use sed to remove some characters and return the result to a variable. But I can't seem to get it to work. Here's what i've tried and the corresponding errors I get.

PROJECT_DB_NAME=`sed -i "${var}"'s/[^a-zA-Z]//g'`

Error sed: -i may not be used with stdin

PROJECT_DB_NAME=`"$var" | sed -n 's/[^a-zA-Z]//g'`

Error domain.com: command not found

I've found lots of example but none do exactly what I want to do and I'm a bit of a bash noob. Thanks

  • 1
    Have you tried removing the -i option? Are you using sed to process a file, or to process the output of some other command? – glenn jackman Jul 1 at 22:45
  • 1
    Your question is not clear, are you trying to set the variable to the return value of sed or the output of sed ? – X Tian Jul 3 at 12:13
1

You don't need sed to remove non-alphabetic characters from the value of a variable in bash. A simple variable substitution will do the same thing:

PROJECT_DB_NAME=${var//[![:alpha:]]}

If you want to use [!a-zA-Z] in place of [![:alpha:], then that is of course also possible.

If you really want to use an external command for removing these characters, use the more light-weight tr rather than sed. The task of tr is exactly to do things like these (single character transliterations).

PROJECT_DB_NAME=$( tr -dc '[:alpha:]' <<<"$var" )

or,

PROJECT_DB_NAME=$( printf '%s\n' "$var" | tr -dc '[:alpha:]' )

See the manual for the tr command.

Note that using echo may alter the contents of the variable before sed sees it. See the question "Why is printf better than echo?".


Your first piece of code,

PROJECT_DB_NAME=`sed -i "${var}"'s/[^a-zA-Z]//g'`

would run sed without a filename. This makes sed assume that data is arriving over standard input. The -i option, as the error message says, can't be used with standard input. Also, you prepend the sed code with the value of the variable. This would make the variable's value be interpreted as sed editing commands.

Your second piece of code,

PROJECT_DB_NAME=`"$var" | sed -n 's/[^a-zA-Z]//g'`

This tries to run "$var" as a command on the left hand side of the pipeline. Also, you use sed -n which will cause sed to not output the modified data by default.

  • Awesome. Thank you for the explanation. – Antony Thompson Jul 2 at 22:29
1

Ok I found the answer here: How to assign result of sed to variable

I had looked at that answer but implemented it wrong at my end. So here's what I ended up with:

PROJECT_DB_NAME=$( echo "$var" | sed 's/[^a-zA-Z]//g')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.