简体   繁体   中英

Awk command to format text output with custom record separator and field Separator

I have a file which has the data in the following manner :

1
2
3
end
4
5
6

I want an output in the form :

1   2   3
4   5   6

here the string "end" represents the record separator. I am new to UNIX and used Awk to achieve this, I am sure there can be much easier and a better way. Here is my attempt:

awk 'BEGIN {RS="end\n"; FS="\n"} { print $1 "\t"  $2 "\t" $3 "\t" $4'} atestfile.awk

Personally I'd write it like this:

awk -v RS='end' -v OFS='\t' '{$1=$1}1' file

The differences are that I've used -v to specify the record separator RS and the output field separator OFS . I've also used $1=$1 to make awk "touch" each record (so that the format is changed to use OFS ) and 1 at the end as a shorthand for {print} (since 1 is always True and the default action of awk on True is to print the record).

I'd probably use perl (and yes, I know that's not quite what you asked, but given it's standard on Unix, I'll offer it anyway).

use strict;
use warnings;

#read STDIN or a filename designated on command line. 
while (<>) { 
    #replace linefeeds with spaces. 
    s/\n/ /g;
    #Check for presence of "end"
    if (m/end/) {
        #insert linefeed
        print "\n";
    }
    else {
        print;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM