输出for循环到文件 [英] Output for loop to a file

查看:105
本文介绍了输出for循环到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将for循环输出到文本输出到文件10次.这是我所拥有的:

I am trying to have a for loop output to a text to a file 10 times. Here is what I have:

for ((i=1;i<=10;i++)) ; do echo "Hello World" > testforloop.txt ;  done

这一次将"Hello World"输出到文件"testforloop.txt".如果我没有输出到文件,它将在屏幕上打印Hello World 10次.感谢您的帮助.

This outputs "Hello World" once to the file "testforloop.txt". If I don't output to file it prints Hello World to the screen 10 times. Thanks for any help.

推荐答案

您正在使用>重定向,它会在循环内擦除文件的现有内容并将其替换为命令的输出.因此,这会擦除之前的内容10次,每次替换为一行.

You are using > redirection, which wipes out the existing contents of the file and replaces it with the command's output, inside the loop. So this wipes out the previous contents 10 times, replacing it with one line each time.

在没有>>/dev/tty的情况下,它将转到您的显示器,其中>无法擦除任何内容,因此您会看到所有十个副本.

Without the >, or with >/dev/tty, it goes to your display, where > cannot wipe anything out so you see all ten copies.

您可以使用>>,它仍然会打开文件十次,但是每次都会附加(而不清除以前的内容).但这并不是十分有效,它可以保留前一次运行的数据(可能是您想要的,也可能不是您想要的).

You could use >>, which will still open the file ten times, but will append (not wipe out previous contents) each time. That's not terribly efficient though, and it retains data from a previous run (which may or may not be what you want).

或者,您可以将整个循环重定向一次:

Or, you can redirect the entire loop once:

for ... do cmd; done >file

运行整个循环,重定向输出,仅创建一次(或使用>>打开追加).

which runs the entire loop with output redirected, creating (or, with >>, opening for append) only once.

这篇关于输出for循环到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆