-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 4 '19 at 6: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 4 '19 at 7:37
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"
| improve this answer | |
  • filename=~/file expands ~ for me as expected in both bash and zsh. – Sparhawk May 4 '19 at 6:27
  • Yes, so the assignment to filename must be quoted. – RalfFriedl May 4 '19 at 9:33
  • Their issue is trying to run the output of set -x (or at least copy-paste it), which shows the filename in single quotes. – Kusalananda May 4 '19 at 9:42
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 ~.

| improve this answer | |

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