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
Looping over input fields as array
提问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
, sed
or perl
. You can easily do this directly in the shell:
不需要awk
,sed
或perl
。您可以直接在 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:
使用这些命令行选项:
-n
loop around each line of the input file, do not automatically print the line-l
removes newlines before processing, and adds them back in afterwards-a
autosplit mode – split input lines into the@F
array. Defaults to splitting on whitespace.-e
execute the perl code
-n
循环输入文件的每一行,不自动打印该行-l
在处理之前删除换行符,然后将它们添加回-a
自动拆分模式 – 将输入行拆分到@F
数组中。默认为在空白处拆分。-e
执行perl代码