Row to column and column to row using awk

后端 未结 4 1900
小鲜肉
小鲜肉 2020-12-19 00:14

I have two files containing as below

cat file1.txt
a b c 
1 2 3

cat file2.txt
a
b
c
1
2
3

I want file1 to be arranged as

a         


        
相关标签:
4条回答
  • 2020-12-19 00:54

    The idiomatic awk approach of simply setting the OFS or ORS to the FS or RS as appropriate before printing (and recompiling the record if necessary with $1=$1) will work with any awk:

    $ cat file1
    a b c
    1 2 3
    $ awk '{OFS=RS;$1=$1}1' file1
    a
    b
    c
    1
    2
    3
    $ cat file2
    a
    b
    c
    1
    2
    3
    $ awk '{ORS=(NR%3?FS:RS)}1' file2
    a b c
    1 2 3
    
    0 讨论(0)
  • 2020-12-19 00:56

    For yout first file, you could try something like :

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

    For your second file, you could try something like :

    awk 'BEGIN {str=""; i=1} {if(i%3 == 0){str=str""$0"\n"} else {str=str""$0" "} i++} END {print str}' file2.txt
    

    However, I'd to make some assumptions like that the whole 3 lines need to skip a line in the output, for example. We would need more details I think ...

    0 讨论(0)
  • 2020-12-19 01:03

    I'd use xargs for this:

    $ xargs -n1 < file1
    a
    b
    c
    1
    2
    3
    
    $ xargs -n3 < file2
    a b c
    1 2 3
    
    0 讨论(0)
  • 2020-12-19 01:04

    Some awk version

    awk 1 RS=" |\n" file1  # gnu awk version
    awk '{for (i=1;i<=NF;i++) print $i}' file1 # portable version
    a
    b
    c
    1
    2
    3
    


    awk '{printf "%s" (NR%3==0?RS:FS),$1}' file2
    a b c
    1 2 3
    

    printf "%s" # print pararameter #1 ($1)
    NR%3==0?"RS:FS # add extra formatting. Test if line is number 3. If its not, use FS (a blank space), if it is use RS, a new line.
    So this adjust the next parameter after every 3 line.

    0 讨论(0)
提交回复
热议问题