在shell脚本中的echo -e命令中获取\ n而不是n

时间:2014-09-15 10:35:39

标签: shell command echo

我正在尝试获取echo -e命令的输出,如下所示

使用的命令:

echo -e "cd \${2}\nfilesModifiedBetweenDates=\$(find . -type f -exec ls -l --time-style=full-iso {} \; | awk '{print \$6,\$NF}' | awk '{gsub(/-/,\"\",\$1);print}' | awk '\$1>= '$fromDate' && \$1<= '$toDate' {print \$2}' | tr \""\n"\" \""\;"\")\nIFS="\;" read -ra fileModifiedArray <<< "\$filesModifiedBetweenDates"\nfor fileModified in \${fileModifiedArray[@]}\ndo\n egrep -w "\$1" "\$fileModified" \ndone"

cd $ {2}

预期输出:

cd ${2}

filesModifiedBetweenDates=$(find . -type f -exec ls -l --time-style=full-iso {} \; | awk '{print $6,$NF}' | awk '{gsub(/-/,"",$1);print}' | awk '$1>= '20140806' && $1<= '20140915' {print $2}' | tr "\n" ";")

IFS=; read -ra fileModifiedArray <<< $filesModifiedBetweenDates

for fileModified in ${fileModifiedArray[@]}

do

egrep -w $1 $fileModified 

done

原始输出:

cd ${2}

filesModifiedBetweenDates=$(find . -type f -exec ls -l --time-style=full-iso {} \; | awk '{print $6,$NF}' | awk '{gsub(/-/,"",$1);print}' | awk '$1>= '20140806' && $1<= '20140915' {print $2}' | tr "n" ";")

IFS=; read -ra fileModifiedArray <<< $filesModifiedBetweenDates

for fileModified in ${fileModifiedArray[@]}

do

 egrep -w $1 $fileModified 

done

我如何处理“\”?

2 个答案:

答案 0 :(得分:1)

对于长文本块,使用此处引用的文档比尝试将多行字符串嵌入到echoprintf的单个参数中要简单得多。

cat <<"EOF"
cd ${2}

filesModifiedBetweenDates=$(find . -type f -exec ls -l --time-style=full-iso {} \; | awk '{print $6,$NF}' | awk '{gsub(/-/,"",$1);print}' | awk '$1>= '20140806' && $1<= '20140915' {print $2}' | tr "\n" ";")

IFS=; read -ra fileModifiedArray <<< $filesModifiedBetweenDates

for fileModified in ${fileModifiedArray[@]}

do

egrep -w $1 $fileModified 

done
EOF

答案 1 :(得分:0)

您最好使用printf来获得更好的控制权:

$ printf "tr %s %s\n" '"\n"' '";"'
tr "\n" ";"

如您所见,我们在双引号中指示参数:printf "text %s %s"然后我们定义应在此参数中存储的内容。

如果您真的必须使用echo,请转义\

$ echo -e 'tr "\\n" ";"'
tr "\n" ";"

有趣的阅读:Why is printf better than echo?