bash Shell 脚本中的 For 循环 - 在 csv 文件中添加断线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/621915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For Loop in Shell Script - add breakline in csv file
提问by Abs
I'm trying to use a forloop in a shell script.
我正在尝试for在 shell 脚本中使用循环。
I am executing a command from a text file. I wish to execute each command 10 times and insert some stats into a csv file. After that command has been done, I want to start the next BUT put a line break in the CSV file after the first command that was done 10 times.
我正在从文本文件执行命令。我希望每个命令执行 10 次并将一些统计信息插入到 csv 文件中。完成该命令后,我想开始下一个但在执行 10 次的第一个命令之后在 CSV 文件中放置一个换行符。
Is the following correct:
以下是否正确:
#Function processLine
processLine(){
line="$@"
for i in 1 2 3 4 5 6 7 8 9 10
do
START=$(date +%s.%N)
echo "$line"
eval $line > /dev/null 2>&1
END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc)
echo "$line, $START, $END, $DIFF" >> file.csv 2>&1
echo "It took $DIFF seconds"
echo $line
done
}
Thanks all for any help
感谢大家的帮助
UPDATE
更新
It is doing the loop correctly, but I can't get it to add a line break after each command is executed 10 times.
它正在正确执行循环,但我无法在每个命令执行 10 次后添加换行符。
回答by Mykola Golubyev
processLine()
{
line="$@"
echo $line >> test_file
for ((i = 1; i <= 10 ; i++))
do
# do not move to the next line
echo -n "$i," >> test_file
done
# move to the next line: add the break
echo >> test_file
}
echo -n > test_file
processLine 'ls'
processLine 'find . -name "*"'
回答by mweerden
How about just adding a line "echo >> file.csv" after done? Or do you only want an empty line between each block of 10? Then you could do the following:
echo >> file.csv在 之后添加一行“ ”done怎么样?或者你只想在每个 10 块之间有一个空行?然后你可以执行以下操作:
FIRST=1
processline()
{
if (( FIRST )) then
FIRST = 0
else
echo >> file.csv
fi
...rest of code...
}
Otherwise you might want to give an example of the desired output and the output you are getting now.
否则,您可能想举例说明所需的输出和您现在得到的输出。
回答by MarkusQ
It looks reasonable. Does it do what you want it to?
看起来很合理。它做你想让它做的事吗?
You could simplify some things, e.g.
你可以简化一些事情,例如
DIFF=$(echo "$END - $START" | bc)
could be just
可能只是
DIFF=$((END - START))
if END and START are integers, and there's no need to put things in variables if you're only going to use them once.
如果 END 和 START 是整数,并且如果您只打算使用它们一次,则无需将内容放入变量中。
If it's notdoing what you want, edit the question to describe the problem (what you see it doing and what you'd rather have it do).
如果它没有做您想要的,请编辑问题以描述问题(您看到它在做什么以及您希望它做什么)。

