开发者

Looping over input fields as array

开发者 https://www.devze.com 2023-03-27 07:23 出处:网络
Is it possible to do something like this: $ cat foo.txt 1 2 3 4 foo bar baz 开发者_StackOverflow中文版hello world

Is it possible to do something like this:

$ cat foo.txt
1 2 3 4
foo bar baz
开发者_StackOverflow中文版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($0,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.


Found out myself:

$ awk '{ for(i = 1; i <= NF; i++) { print $i; } }' foo.txt


I'd use sed:

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


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

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


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

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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消