printf以错误的顺序打印我的变量,换行符不起作用。在对不同的printf语句进行迭代之后,它仍然无法工作,而且我也不太确定出了什么问题。
这是我目前的代码:
cat ~/data/quotes.csv | while IFS=, read author quote; do
author_s=$(echo $author | cut -d'"' -f 2) # removes quotations - e.g. turns "Jonathan Kozol" to Jonathan Kozol
printf "$quote\n\t~$author_s"
done | sort -R | tail -1 # print one random line from quotes.csv这是我的输出(我也不确定是什么导致了错误):
-bash: printf: `w': invalid format character
~ Jonathan Kozol"Don't compromise yourself. You are all you've got."然而,我想以这样的方式结束:
"Don't compromise yourself. You are all you've got."
~ Jonathan Kozol另外,当我尝试在不同的行上打印变量$author_s和$quote时
例如:
printf "$quote\n"
printf "$author_s"作者不打印
quotes.csv的第一部分
"Author","Quote"
"Thomas Edison","Genius is one percent inspiration and ninety-nine percent perspiration."
"Yogi Berra","You can observe a lot just by watching."
"Abraham Lincoln","A house divided against itself cannot stand."
"Johann Wolfgang von Goethe","Difficulties increase the nearer we get to the goal."
"Byron Pulsifer","Fate is in your hands and no one elses"
"Lao Tzu","Be the chief but never the lord."
"Carl Sandburg","Nothing happens unless first we dream."
"Aristotle","Well begun is half done."
"Yogi Berra","Life is a learning experience, only if you learn."
"Margaret Sangster","Self-complacency is fatal to progress."
"Buddha","Peace comes from within. Do not seek it without."发布于 2020-11-06 09:58:36
printf的第一个参数应该包含格式字符串。您的特定格式将是"%s\n\t~ %s\n"。
%s是实际引用的\n\t换行符和选项卡~ %s\n a tilde,作者和换行符示例:
#!/bin/bash
while IFS=, read -r author quote
do
author="${author%\"}" # remove first "
author="${author#\"}" # remove last "
printf "%s\n\t~ %s\n" "$quote" "$author"
done < quotes.csv为了选择一个随机引号,可以使用shuf
#!/bin/bash
tail -n +2 quotes.csv | shuf -n1 | while IFS=, read -r author quote
do
author="${author%\"}" # remove first "
author="${author#\"}" # remove last "
printf "%s\n\t~ %s\n" "$quote" "$author"
done在这里,tail -n +2 quotes.csv跳过文件中的第一行("Author","Quote"),shuf -n1选择一条随机行。
第二个例子,但是使用过程替代代替:
#!/bin/bash
while IFS=, read -r author quote
do
author="${author%\"}" # remove first "
author="${author#\"}" # remove last "
printf "%s\n\t~ %s\n" "$quote" "$author"
done < <(shuf -n1 <(tail -n +2 quotes.csv))https://stackoverflow.com/questions/64711972
复制相似问题