bash 循环遍历空格分隔字符串的简单 Unix 方式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25870689/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:40:28  来源:igfitidea点击:

Simple Unix way of looping through space-delimited strings?

bashunixsh

提问by Sibbs Gambling

I have a file, called file_list, containing space-delimited strings, each of which is a file name of a file to be processed. I now wish to loop through all the file names and process them one by one. Pseudocode is

我有一个名为 的文件,file_list其中包含以空格分隔的字符串,每个字符串都是要处理的文件的文件名。我现在希望遍历所有文件名并一一处理它们。伪代码是

for every filename in file_list
    process(filename);
end

I have come up with a rather clumsy solution, which is

我想出了一个相当笨拙的解决方案,那就是

  1. load the file into a variable by filenames='cat file_list'
  2. count the number of spaces, N, by tr -cd ' ' <temp_list | wc -c
  3. loop from 1 to Nand parse by space each file name out with cut
  1. 将文件加载到变量中 filenames='cat file_list'
  2. 计算空格数, N, bytr -cd ' ' <temp_list | wc -c
  3. 从 1 循环到N并按空格解析每个文件名cut

Is there an easier/more elegant way of doing this?

有没有更简单/更优雅的方法来做到这一点?

回答by randomusername

The easiest way to do it is a classic trick that's been in the bourne shell for a while.

最简单的方法是在 bourne shell 中使用了一段时间的经典技巧。

for filename in `cat file_list`; do
  # Do stuff here
done

回答by fedorqui 'SO stop harming'

You can change the file to have words be line separated instead of space separated. This way, you can use the typical syntax:

您可以将文件更改为行分隔而不是空格分隔单词。这样,您可以使用典型的语法:

while read line
do
   do things with $line
done < file

With tr ' ' '\n' < fileyou replace spaces with new lines, so that this should make:

随着tr ' ' '\n' < file您更换新线路的空间,所以,这应该:

while read line
do
   do things with $line
done < <(tr ' ' '\n' < file)

Test

测试

$ cat a
hello this is a set of strings
$ while read line; do echo "line --> $line"; done < <(tr ' ' '\n' < a)
line --> hello
line --> this
line --> is
line --> a
line --> set
line --> of
line --> strings