zsh:在括号前保留斜线

zsh: keep slash before parenthesis

我需要从文件中缓存一个字符串以便稍后进行 grep 搜索。该字符串在括号前有一个斜杠。在我抓取字符串并在 shell 中回显它之后,它的行为符合我的预期;但在我的脚本中它去掉了斜杠。

下面有很多文字,但字符串中重要的部分是“(remainingTime)”

文件中的行:

"session_will_expire_message" = "User session will expire in \(remainingTime). Please sign in again to avoid expiration in the middle of the transaction.";

Shell 命令(按预期工作):

% line="\"User session will expire in \(remainingTime). Please sign in again to avoid expiration in the middle of the transaction.\";"
% echo $line
"User session will expire in \(remainingTime). Please sign in again to avoid expiration in the middle of the transaction.";
% echo -E - $line
"User session will expire in \(remainingTime). Please sign in again to avoid expiration in the middle of the transaction.";
% val="$(echo -E - $line | cut -d";" -f1 | cut -d"=" -f2-)"
% echo $val
"User session will expire in \(remainingTime). Please sign in again to avoid expiration in the middle of the transaction."
% echo -E - "${val}"
"User session will expire in \(remainingTime). Please sign in again to avoid expiration in the middle of the transaction."

脚本(未按预期工作):

while read line; do
    if [[ $(echo $line | grep -c "=") -gt 0 ]]; then
        key="$(echo $line | cut -d";" -f1 | cut -d"=" -f1 | tr -d " ")"
        val="$(echo -E - $line | cut -d";" -f1 | cut -d"=" -f2-)"
/* !!--> */ [[ $IS_VERBOSE == "TRUE" ]] && echo "key: $key" && echo -E - "value: ${val}"                
/* !!--> */ [[ $key != "" && "${val}" != "" ]] && LOCALIZED_PAIR[$key]="${val}"
    fi
done < $LOCALIZED_DICT   # <-- This is an URI for .strings file

标有“!! -->”的行输出到 shell 和一个没有斜杠的文件...

key: "session_will_expire_message"

value: "User session will expire in (remainingTime). Please sign in again to avoid expiration in the middle of the transaction."

为什么我的脚本工作方式不同,我该如何解决?

编辑:

斜杠似乎被 while 循环去掉了:

% while read l; do echo $l; done < ~/Desktop/tmpOutput 
"User session will expire in (remainingTime). Please sign in again to avoid expiration in the middle of the transaction.";

如果 while 循环读取该行时斜线被拆分,有没有办法避免这种情况?

你有很多不必要的额外进程。但是,除此之外,使用 -r 选项来防止 read 处理输入中的任何反斜杠。

while IFS== read -r key val; do
    [[ -z $key || -z $val ]] && continue
    if [[ $IS_VERBOSE == TRUE ]]; then
        print -r "key: $key"
        print -r "value: $val"
    fi
    LOCALIZED_PAIR[$key]=$val
done < "$LOCALIZED_DICT"