简体   繁体   English

在bash中循环文件内容

[英]Looping file contents in bash

I have a file /tmp/a.txt whose contents I want to read in a variable many number of times.我有一个文件 /tmp/a.txt ,我想多次读取它的内容。 If the EOF is reached then it should start from the beginning.如果达到 EOF,那么它应该从头开始。

ie If the contents of the file is "abc" and I want to get 10 chars, it should be "abcabcabca".即如果文件的内容是“abc”并且我想获得 10 个字符,它应该是“abcabcabca”。

For this I wrote an obvious script:为此,我写了一个明显的脚本:

while [ 1 ]; 
  do cat /tmp/a.txt; 
done | 
for i in {1..3}; 
  do read -N 10 A; 
  echo "For $i: $A"; 
done

The only problem is that it hangs!唯一的问题是它挂了! I have no idea why it does so!我不知道为什么会这样!

I am also open to other solutions in bash.我也对 bash 中的其他解决方案持开放态度。

To repeat over and over a line you can :要一遍又一遍地重复一行,您可以:

yes "abc" | for i in {1..3}; do read -N 10 A; echo "for $i: $A"; done

yes will output 'forever', but then the for i in 1..3 will only execute the "do ... done;" yes 将输出 'forever',但是 1..3 中的 for i 将只执行“do ... done;” part 3 times第 3 部分

yes add a "\\n" after the string.是的,在字符串后添加一个“\\n”。 If you don't want it, do:如果您不想要它,请执行以下操作:

 yes "abc" | tr -d '\n' | for i in {1..3}; do read -N 10 A; echo "for $i: $A"; done

In all the above, note that as the read is after a pipe, in bash it will be in a subshell, so "$A" will only available in the "do....done;"在上述所有内容中,请注意,由于读取是在管道之后,因此在 bash 中它将位于子外壳中,因此“$A”仅在“do....done;”中可用。 area, and be lost after!区域,然后迷路!

To loop and read from a file, and also not do that in a subshell:要循环并从文件中读取,也不要在子 shell 中执行此操作:

for i in {1..3}; do read -N 10 A ; echo "for $i: $A"; done <$(cat /the/file)

To be sure there is enough data in /the/file, repeat at will:为确保 /the/file 中有足够的数据,请随意重复:

for i in {1..3}; do read -N 10 A ; echo "for $i: $A"; done <$(cat /the/file /the/file /the/file)

To test the latest: echo -n "abc" > /the/file (-n, so there is no trainling newline)测试最新的: echo -n "abc" > /the/file (-n, 所以没有训练换行符)

The script hangs because of the first loop.由于第一个循环,脚本挂起。 After the three iterations of the second loop (for) are done, the first loop repeatedly starts new cat instances which read the file and then write the content abc to the pipe.在第二个循环 (for) 的三个迭代完成后,第一个循环重复启动新的cat实例,这些实例读取文件,然后将内容abc写入管道。 The write to the pipe doesn't work any more in the later iterations.在以后的迭代中,对管道的写入不再起作用。 Yes, there is a SIGPIPE kill, but to the cat command and not to the loop itself.是的,有一个 SIGPIPE 终止,但是针对cat命令而不是循环本身。 So the solution is to catch the error in the right place:所以解决方案是在正确的地方捕捉错误:

while [ 1 ]; 
  do cat /tmp/a.txt || break
done | 
for i in {1..3}; 
  do read -N 10 A; 
  echo "For $i: $A"; 
done

Besides: output is following:此外:输出如下:

For 1: abcabcabca
For 2: bcabcabcab
For 3: cabcabcabc
<-- (Here the shell hangs no more)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM