-1

I have a shell script that's executing a sed command. Upon variable expansion, it quotes the filename.

sed -i "$3d" $filename

becomes

sed -i 1d '~/file'

as shown by the debugging flag -x.

When ran, this produces

sed: can't read ~/file: No such file or directory

When I try to run the command manually, the same thing happens, unless I remove the quotes.

sed -i 1d ~/file

Running without quotes produces the desired output.

  • Please post the part where you assign the variables. Also, what is "the debugging flag -x"? My version of sed doesn't appear to have this. – Sparhawk May 04 '19 at 06:26
  • I've closed this as a duplicate. In addition to tilde not expanding when it's quoted, the output produced under set -x is not on a form suitable for execution. It's is purely shell tracing output. – Kusalananda May 04 '19 at 07:37

2 Answers2

1

The problem are the quotation marks around the filename. They prevent your shell to expand ~ to your home folder. So sed is looking for a folder called ~.

Make sure $filename doesn't contain the quotation mark or use the real path instead of ~.

0

The problem here is the part that you don't show. Somewhere before that line you have something like this:

filename="~/file"

So the problem is not that the later use of $filename is quoted, it isn't quoted and that can introduce other problems if the name contains spaces.

The ~ is expanded by the shell to the home directory if it is the first character of a word. It is not expanded if it is the result of a variable expansion.

You can use $HOME instead of ~:

filename=$HOME/file
sed -i "$3d" $filename

or better with quotes:

filename="$HOME/file"
sed -i "$3d" "$filename"
RalfFriedl
  • 8,981