【问题标题】:space containing items in bash for-loopbash for循环中包含项目的空间
【发布时间】:2015-02-05 13:49:39
【问题描述】:

我想将./src/下的所有markdown文件递归转换为html:

#!/bin/bash

function do_recursive_pandoc {
local markdown_src_file_extension=\*.markdown
local markdown_src_path="$1"
local html_output_path="$2"
mkdir "$html_output_path" 2>/dev/null

for i in $(find $markdown_src_path -name $markdown_src_file_extension 2>/dev/null | cut --delimiter='/' --fields=2- )
do
    mkdir "$html_output_path"/$(dirname "$i") 2>/dev/null
    pandoc -rmarkdown -whtml "$markdown_src_path"/"$i" --output="$html_output_path"/"$i".html
done

}

do_recursive_pandoc "src" "output"

但如果我在文件路径或名称中有空格,bash 会将它们视为for 循环中的多个项目,例如,如果我有:

./src/dir 1/foo.markdown

此脚本将创建./output/1 目录而不是创建./output/dir 1/ 并尝试转换./src/dir./src/1/foo.markdown 而不是./src/dir 1/foo.markdown

我该如何解决这个问题?

【问题讨论】:

标签: bash for-loop whitespace filenames filepath


【解决方案1】:

你最好在这样的时候找到管道:

find $markdown_src_path -name $markdown_src_file_extension 2>/dev/null | cut --delimiter='/' --fields=2- | while read i; do

【讨论】:

  • 你也应该使用read -r,以防文件名中还有其他有问题的字符。
【解决方案2】:

这样就可以了:

#!/bin/bash
#############################################################################
function do_recursive_pandoc {
    local src_path=$(realpath "$1") 
    local output_path=$(realpath "$2") && mkdir --parents "$output_path" 2>/dev/null
    find "$src_path" -name "*.markdown" -not -path "$output_path" -exec bash -c '
        i=$1
        o="$3""${1#$2}"
        mkdir --parents "$(dirname "$o")" 2>/dev/null
        if [ -f "$i" ]; then pandoc -rmarkdown -whtml "$i" --output="$o".html ; fi
        ' " " {} $src_path $output_path \;
}
#############################################################################
do_recursive_pandoc "src" "output"
#############################################################################

我将它与基本 CSS 一起粘贴到 Gist

【讨论】:

    猜你喜欢
    • 2014-05-27
    • 1970-01-01
    • 2017-04-11
    • 2020-01-06
    • 2015-12-23
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多