printfは文字列%qと変数をエスケープします。

printfは文字列%qと変数をエスケープします。

スペースを使用してパスをエスケープしたいです。次のように直接使用するとうまく機能します。

$ printf '%q' "/path/to/first dir/dir/"
/path/to/first\ dir/dir/

文字列の代わりに変数を使用すると、空白のない文字列が返されます。

$ testpath="/path/to/first dir/dir/" && printf '%q' $testpath
/path/to/firstdir/dir/

printfと変数を使用してパスからスペースをエスケープする方法はありますか?それとも、awk/sed/regexを使用しない他の単純なソリューションはありますか?

ベストアンサー1

変数を参照する必要があります。

testpath="/path/to/first dir/dir/" && printf '%q' "$testpath"

おすすめ記事