Awk: extract different columns from many different files

前端 未结 3 1346
北恋
北恋 2020-12-09 06:40

File Example

I have a 3-10 amount of files with:

 - different number of columns
 - same number of rows
 - inconsistent spacing (sometimes o         


        
3条回答
  •  长情又很酷
    2020-12-09 07:29

    Assuming each of your files has the same number of rows, here's one way using GNU awk. Run like:

    awk -f script.awk file1.txt file2.txt file3.txt file4.txt
    

    Contents of script.awk:

    FILENAME == ARGV[1] { one[FNR]=$1 }
    FILENAME == ARGV[2] { two[FNR]=$3 }
    FILENAME == ARGV[3] { three[FNR]=$7 }
    FILENAME == ARGV[4] { four[FNR]=$1 }
    
    END {
        for (i=1; i<=length(one); i++) {
            print one[i], two[i], three[i], four[i]
        }
    }
    

    Note:

    By default, awk separates columns on whitespace. This includes tab characters and spaces, and any amount of these. This makes awk ideal for files with inconsistent spacing. You can also expand the above code to include more files if you wish.

提交回复
热议问题