Looping over input fields as array

前端 未结 4 1123
夕颜
夕颜 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:10

    Found out myself:

    $ awk '{ for(i = 1; i <= NF; i++) { print $i; } }' foo.txt
    
    0 讨论(0)
  • 2021-01-03 19:12

    I'd use sed:

    sed 's/\ /\n/g' foo.txt
    
    0 讨论(0)
  • 2021-01-03 19:19

    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
    
    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题