unix - How to swap the lines in a file that match a condition using Shell script -
i have file in 28th character of every line either "a" or "d". want swap lines in such way first line of file should have 28th character "d" , second line of file should have 28 character "a". , pattern should continue through out file.
input file:
00254920141228n201412251850a201412241740sa1118we1440scl 00254920141228n201412251850d201412200050sa1150th1850000 00254920141228r201412251850a201412241740sa1118we1440scl 00254920141228r201412251850a201412241740sa1118we1440scl 00254920141228r201412251850d201412200050sa1150th1850000 00254920141228r201412251850d201412200050sa1150th1850000 output should be:
00254920141228n201412251850d201412200050sa1150th1850000 00254920141228n201412251850a201412241740sa1118we1440scl 00254920141228r201412251850d201412200050sa1150th1850000 00254920141228r201412251850a201412241740sa1118we1440scl 00254920141228r201412251850d201412200050sa1150th1850000 00254920141228r201412251850a201412241740sa1118we1440scl i want script written in unix shell script.
here simple python script implements think trying describe.
from sys import stdin keep = "a" kept = [] line in stdin: line = line.rstrip("\r\n") pattern = line[27:28] # print("## keep %s, pattern %s, %s" % (keep, pattern, line)) if pattern != keep: if len(kept) > 0: print line # print("### len kept == %i, popping" % len(kept)) print kept.pop(0) else: # print("### no kept, print") print line keep = pattern else: # print("### keeping later") keep = pattern kept.append(line) if len(kept) > 1: raise valueerror("too many %s lines" % keep) elif len(kept) == 1: print kept[0] i left debug prints in can see what's happening -- uncomment print statements # in them bit of debug diagnostics if doesn't want.
i started writing awk script simplicity, awk arrays don't have push/pop, turned out more complex liked.
i not use sed this. don't doubt it's doable, hard maintain, if not , colleagues committing maintaining high fluency in sed. (that's nicer way "write-only language"...)
i consistently used double quotes python strings. way, can embed single-quoted in simple shell script testing, this:
#!/bin/sh python -c '... text of script' <<':' sample data :
Comments
Post a Comment