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

后端 未结 8 1767
谎友^
谎友^ 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:18

    If you want to edit a file, you can use ed, the standard editor. Your task is rather easy in ed:

    printf '%s\n' 14m26 26-m14- w q | ed -s file
    

    How does it work?

    • 14m26 tells ed to take line #14 and move it after line #26
    • 26-m14- tells ed to take the line before line #26 (which is your original line #26) and move it after line preceding line #14 (which is where your line #14 originally was)
    • w tells ed to write the file
    • q tells ed to quit.

    If your numbers are in a variable, you can do:

    linea=14
    lineb=26
    {
        printf '%dm%d\n' "$linea" "$lineb"
        printf '%d-m%d-\n' "$lineb" "$linea"
        printf '%s\n' w q
    } | ed -s file
    

    or something similar. Make sure that linea.

提交回复
热议问题