bashunixawksedtext-files

Unix one-liner to swap/transpose two lines in multiple text files?


I wish to swap or transpose pairs of lines according to their line-numbers (e.g., switching the positions of lines 10 and 15) in multiple text files using a UNIX tool such as sed or awk.

For example, I believe this sed command should swap lines 14 and 26 in a single file:

sed -n '14p' infile_name > outfile_name
sed -n '26p' infile_name >> outfile_name

How can this be extended to work on multiple files? Any one-liner solutions welcome.


Solution

  • This might work for you (GNU sed):

    sed -ri '10,15!b;10h;10!H;15!d;x;s/^([^\n]*)(.*\n)(.*)/\3\2\1/' f1 f2 fn
    
    # or as multiple lines:
    
    sed -ri '
        10,15!b
        10h
        10!H
        15!d
        x
        s/^([^\n]*)(.*\n)(.*)/\3\2\1/
    ' f1 f2 fn
    

    This stores a range of lines in the hold space and then swaps the first and last lines following the completion of the range.

    The i flag edits each file (f1,f2 ... fn) in place.


    Alternative:

    sed -Ei '10{:a;N;15!ba;s/([^\n]*)(.*\n)(.*)/\3\2\1/}' file1 file2 filen
    

    Another using parallel, bash and ed:

    parallel "ed -s {} <<<$'7m5\n5m7\nwq'" ::: file1 file2 filen