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.
-i
option? Are you using sed to process a file, or to process the output of some other command? – glenn jackman Jul 01 '19 at 22:45