0

Each line starts with FEPS. Merge the line which doesn't start with FEPS to previous line and then sort the file based on length i.e; keep the lines whose length is 23 chars

Input:

FEPS xxxx01 BUILDING 0 
FEPS xxxx02 BUILDING 
FEPS xxxx03 BUILDING 
0 
FEPS xxxx04 BUILDING 0 

Output:

FEPS xxxx01 BUILDING 0 
FEPS xxxx03 BUILDING 0 
FEPS xxxx04 BUILDING 0 

Used below script it worked:

awk 'BEGIN
    /FEPS/ {
        if (NR>1) print ""
        printf "%s", $0
        next
    } 
    {printf ",%s", $0} 
    END {print " "}'

Output of the above script should be passed to below

awk 'length ==23 {print $0}'
2
  • Also, please clarify what should happen if the current line is not 140 characters and the next line is also not 140 characters. You say "but if the next line length is 140 then delete the line", which suggests that if the next line is not 140 then the current line should be kept. Don't you want to simply remove any line that isn't exactly 140 characters long? And how do you define characters? Is this ASCII or can you have complex multi-character unicode glyphs?
    – terdon
    Commented Mar 30, 2021 at 21:32
  • execute your scripts in this way, i.e, pass the first script output to next script first script | second script Commented Mar 31, 2021 at 6:02

2 Answers 2

0
$ cat tst.awk
$1 == "FEPS" { prt(); rec="" }
{ rec = rec $0 }
END { prt() }

function prt() { if (length(rec) == 23) print rec }

$ awk -v n=23 -f tst.awk file
FEPS xxxx01 BUILDING 0
FEPS xxxx03 BUILDING 0
FEPS xxxx04 BUILDING 0
0

There's no need to use two awk scripts to do this, one is enough.

awk 'length($0) == 23 { print ; next };
     /^FEPS/ { line=$0; next };
     {
       line = line $0;
       if (length(line) == 23) print line;
       line="";
     }
    ' input

Output, after saving your sample input to a file called input:

FEPS xxxx01 BUILDING 0
FEPS xxxx03 BUILDING 0
FEPS xxxx04 BUILDING 0
2
  • There is a trailing blank char at the end of every line in the posted sample input/output, hence the "23".
    – Ed Morton
    Commented Mar 31, 2021 at 16:08
  • @EdMorton yeah, i deleted the trailing spaces when i copied the sample, thought they were just a copy-paste artifact
    – cas
    Commented Mar 31, 2021 at 21:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .