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

后端 未结 8 1777
谎友^
谎友^ 2021-01-06 03:22

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 a

8条回答
  •  借酒劲吻你
    2021-01-06 04:22

    If the line numbers to be swapped are fixed then you might want to try something like the sed command in the following example to have lines swapped in multiple files in-place:

    #!/bin/bash
    
    # prep test files
    for f in a b c ; do
        ( for i in {1..30} ; do echo $f$i ; done ) > /tmp/$f
    done
    
    sed -i -s -e '14 {h;d}' -e '15 {N;N;N;N;N;N;N;N;N;N;G;x;d}' -e '26 G' /tmp/{a,b,c}
    # -i: inplace editing
    # -s: treat each input file separately
    # 14 {h;d} # first swap line: hold ; suppress
    # 15 {N;N;...;G;x;d} # lines between: collect, append held line; hold result; suppress
    # 26 G # second swap line: append held lines (and output them all)
    
    # dump test files
    cat /tmp/{a,b,c}
    

    (This is according to Etan Reisner's comment.)

提交回复
热议问题