在文件名中重新插入转义符,并通过bash脚本将空格打印到终端

在文件名中重新插入转义符,并通过bash脚本将空格打印到终端,bash,shell,Bash,Shell,我的bash脚本获取带有空格和其他奇数字符的文件名 如何将这些文件名打印回终端,并将转义符放在正确的位置,以便用户只需复制和重新粘贴文件名,就可以将其作为参数重新用于相同或其他脚本 我编写了一个测试脚本,内容如下: #! /bin/bash echo "" echo "testing the insertion of '\' in filenames having spaces" echo "the parameter you gave was: '$1'"

我的bash脚本获取带有空格和其他奇数字符的文件名

如何将这些文件名打印回终端,并将转义符放在正确的位置,以便用户只需复制和重新粘贴文件名,就可以将其作为参数重新用于相同或其他脚本

我编写了一个测试脚本,内容如下:

    #! /bin/bash

    echo ""
    echo "testing the insertion of '\' in filenames having spaces"
    echo "the parameter you gave was: '$1'"
    echo "when printed directly the filename looks like: '$1'"
    echo "when printed with echo \$(printf '%q' $x) it looks like: " $(printf '%q' $1)
    bash test.sh this\ filename\ has\ spaces
    testing the insertion of '\' in filenames having spaces

    the parameter you gave was: 'this filename has spaces'
    when printed directly the filename looks like: 'this filename has spaces'
    when printed with echo $(printf '%q' ) it looks like:  thisfilenamehasspaces
运行脚本的过程如下所示:

    #! /bin/bash

    echo ""
    echo "testing the insertion of '\' in filenames having spaces"
    echo "the parameter you gave was: '$1'"
    echo "when printed directly the filename looks like: '$1'"
    echo "when printed with echo \$(printf '%q' $x) it looks like: " $(printf '%q' $1)
    bash test.sh this\ filename\ has\ spaces
    testing the insertion of '\' in filenames having spaces

    the parameter you gave was: 'this filename has spaces'
    when printed directly the filename looks like: 'this filename has spaces'
    when printed with echo $(printf '%q' ) it looks like:  thisfilenamehasspaces
我希望看到脚本生成的是:

    when printed directly the filename looks like: 'this\ filename\ has\ spaces'
看起来很简单,但这个问题对于谷歌来说很难形成。谢谢你的帮助。谢谢。

这是:

printf '%q' $1
这意味着:

printf '%q' this filename has spaces
printf '%q' thisfilenamehasspaces
由于
printf“%q”
连接了它的参数,这意味着:

printf '%q' this filename has spaces
printf '%q' thisfilenamehasspaces
你想要的是:

printf '%q' "$1"
它告诉printf“%q”这个文件名有空格是一个参数,所以它会引用里面的空格

我还建议将命令替换放在双引号内:

echo "when printed with echo \$(printf '%q' $x) it looks like: $(printf '%q' "$1")"
在这种情况下,这恰好不是必需的,但是如果文件名中有一个字符导致
printf“%q”
使用
$”…
-样式引用而不是反斜杠,则这是必需的。

这:

printf '%q' $1
这意味着:

printf '%q' this filename has spaces
printf '%q' thisfilenamehasspaces
由于
printf“%q”
连接了它的参数,这意味着:

printf '%q' this filename has spaces
printf '%q' thisfilenamehasspaces
你想要的是:

printf '%q' "$1"
它告诉printf“%q”这个文件名有空格是一个参数,所以它会引用里面的空格

我还建议将命令替换放在双引号内:

echo "when printed with echo \$(printf '%q' $x) it looks like: $(printf '%q' "$1")"

这在这种情况下是不必要的,但是,如果文件名中有一个字符导致
printf“%q”
使用
$”…“
-样式的引号而不是反斜杠,则这是必需的。

在将参数呈现给printf时,您可能需要双引号。为了清楚起见,我正在尝试将转义字符插入到输出中,以便输出可以被删除由用户剪切并粘贴回bash shell的命令行。在向printf显示参数时,您可能需要双引号引用参数。请澄清,我正在尝试将转义字符插入到输出中,以便用户可以将输出剪切并粘贴回bash shell的命令行。非常感谢您为我节省了大量时间几个小时的搜索。谢谢你为我节省了几个小时的搜索时间。