bash 将输入字段作为数组循环

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

Looping over input fields as array

bashawk

提问by Tyilo

Is it possible to do something like this:

是否有可能做这样的事情:

$ cat foo.txt
1 2 3 4
foo bar baz
hello world
$ awk '{ for(i in $){ print $[i]; } }' foo.txt
1
2
3
4
foo
bar
baz
hello
world

I know you could do this:

我知道你可以这样做:

$ awk '{ split(
$ awk '{ for(i = 1; i <= NF; i++) { print $i; } }' foo.txt
,array," "); for(i in array){ print array[i]; } }' foo.txt 2 3 4 1 bar baz foo world hello

But then the result is not in order.

但随后的结果并不顺利。

回答by Tyilo

Found out myself:

自己发现:

for i in $(cat foo.txt); do echo "$i"; done

回答by Sven Marnach

No need for awk, sedor perl. You can easily do this directly in the shell:

不需要awk,sedperl。您可以直接在 shell 中轻松执行此操作:

sed 's/\ /\n/g' foo.txt

回答by dala

I'd use sed:

我会使用 sed:

perl -lane 'print $_ for @F' foo.txt
perl -lane 'print join "\n",@F' foo.txt

回答by Chris Koknat

If you're open to using Perl, either of these should do the trick:

如果您愿意使用 Perl,那么以下任一方法都可以解决问题:

##代码##

These command-line options are used:

使用这些命令行选项:

  • -nloop around each line of the input file, do not automatically print the line
  • -lremoves newlines before processing, and adds them back in afterwards
  • -aautosplit mode – split input lines into the @Farray. Defaults to splitting on whitespace.
  • -eexecute the perl code
  • -n循环输入文件的每一行,不自动打印该行
  • -l在处理之前删除换行符,然后将它们添加回
  • -a自动拆分模式 – 将输入行拆分到@F数组中。默认为在空白处拆分。
  • -e执行perl代码