Looping over input fields as array

前端 未结 4 1146
夕颜
夕颜 2021-01-03 19:04

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
         


        
4条回答
  •  死守一世寂寞
    2021-01-03 19:26

    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

提交回复
热议问题