2016-07-15 62 views
0

这个问题听起来像是重复的,但我认为它与我找到的页面不同。我试图将一个文本文件的内容分配给一个bash变量,但是我希望将“\ n”字符作为一个字符串包含进来,而不是实际在新行中看到它。例如,文件的内容是这个样子:从字符串文字中赋值变量newline

这里是文本文件的内容

有多种线路

等等等等

我想下面的变量“text_file”将被分配文件的内容,所以当我在脚本中使用它时,它看起来像这样:

这里是文本文件\ nThere的内容是多行\ nblah等等等等

我使用下面的脚本这个变量,我得到这个错误,我相信这是一个结果我分配给变量的“hello.txt”文件中的换行符。

错误解析参数 '--message':无效的JSON:无效的控制字符U '\ N' 在:

subject="Test Email Sent Via AWS" 
message="here is the message to the user...\n\n" 
text_file=`cat hello.txt` 
full_message="$message$text_file" 

cat <<EOF > generated_message.json 
{ 

    "Subject": { 
     "Data": "$subject", 
     "Charset": "UTF-8" 
    }, 
    "Body": { 
     "Text": { 
      "Data": "$full_message", 
      "Charset": "UTF-8" 
     } 
    } 
} 
EOF 
aws ses send-email --profile sendmail --from [email protected] --destination file://destination.json --message file://generated_message.json 

我想我失去了一些东西基本的,但我可以”弄明白了。先谢谢您的帮助。

+0

我不认为这是一个重复的问题,但它确实给了我一些关于可能导致问题的附加信息。因此,如果我在该文章中正确理解了这些回复,那么在JSON中就不能有“\ n”字符,并且需要使用额外的反斜杠进行转义?如果是这样,是否意味着我需要替换原来的所有换行符“你好。txt“文件加上”\\ n“来解决? – syang

回答

1

不要试图用传统的Unix工具将有效的JSON放在一起;使用专为JSON设计的工具,如jq

subject="Test Email Sent Via AWS" 
message="here is the message to the user..." 

jq -R --slurp \ 
    --arg message "$message" \ 
    --arg subject "$subject" '{ 
     "Subject": { 
      "Data": $subject, 
      "Charset": "UTF-8" 
     }, 
     "Body": { 
      "Text": { 
       "Data": ($message + "\n\n" + @text), 
       "Charset": "UTF-8" 
      } 
     } 
    }' <hello.txt> generated_message.json 

-R--slurp确保hello.txt内容直接传递给@text功能,确保文本正确引述JSON字符串。将消息和主题作为变量传递,而不是直接将它们嵌入到过滤器参数中,以确保它们也可以正确编码。

0

内容的text_file

Here is the content of the text file 
There are multiple lines 
blah blah blah 

预计ouptut

Here is the content of the text file\nThere are multiple lines\nblah blah blah 

你可能会做

declare -a file_as_array 
while read line 
do 
file_as_array+=("${line/%/\\n}") 
done<text_file 
file_as_text="$(sed 's/\\n /\\n/g' <<<"${file_as_array[@]}")" 
unset file_as_array 
echo "$file_as_text" 

实际输出

Here is the content of the text file\nThere are multiple lines\nblah blah blah\n 
+0

通过数组的间接方式是什么?只需'file_as_text = $(perl -pe's/\ n/\\ n /'text_file)'应该可以解决这个问题。 – tripleee