在Bash变量中替换换行符?

38

我正在尝试理解带有cdargs包的"cdargs-bash.sh"脚本。在下面的函数中,我有一个问题:

function _cdargs_get_dir ()
{
local bookmark extrapath
# if there is one exact match (possibly with extra path info after it),
# then just use that match without calling cdargs
if [ -e "$HOME/.cdargs" ]; then
    dir=`/bin/grep "^$1 " "$HOME/.cdargs"`
    if [ -z "$dir" ]; then
        bookmark="${1/\/*/}"
        if [ "$bookmark" != "$1" ]; then
            dir=`/bin/grep "^$bookmark " "$HOME/.cdargs"`
            extrapath=`echo "$1" | /bin/sed 's#^[^/]*/#/#'`
        fi
    fi
    [ -n "$dir" ] && dir=`echo "$dir" | /bin/sed 's/^[^ ]* //'`
fi
if [ -z "$dir" -o "$dir" != "${dir/
/}" ]; then
    # okay, we need cdargs to resolve this one.
    # note: intentionally retain any extra path to add back to selection.
    dir=
    if cdargs --noresolve "${1/\/*/}"; then
        dir=`cat "$HOME/.cdargsresult"`
        /bin/rm -f "$HOME/.cdargsresult";
    fi
fi
if [ -z "$dir" ]; then
    echo "Aborted: no directory selected" >&2
    return 1
fi
[ -n "$extrapath" ] && dir="$dir$extrapath"
if [ ! -d "$dir" ]; then
    echo "Failed: no such directory '$dir'" >&2
    return 2
fi

这是一个闭合段落标签。

测试的目的是什么:

"$dir" != "${dir/
/}"

这里的测试跨越了两行;它是想要删除$dir中的换行符,还是出于其他原因?我刚开始学习bash脚本,已经搜索了一段时间,但找不到像这样使用的例子。

1个回答

75

没错,它会删除换行符。我认为测试的目的是确保 $dir 不包含多行。

或者你也可以通过以下方式删除 \newline

${dir/$'\n'/}

这不需要两行,所以我认为它看起来更好。


1
好的,你提供的建议非常有效。这里的 $'\n' 是变量替换吗?我只是无法理解它。 - yorua007
7
不,它被称为“ANSI-C引用”,请参见http://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-Quoting。 - Mu Qiao
1
这只替换第一个(而不是所有)换行符的出现。 - con-f-use
25
@con-f-use ${dir//$'\n'/}将替换所有出现的文本。 - kkpattern
1
dir=${dir/$'\n'/} - OZZIE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接