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
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 #2626-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 fileq
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