Search code examples
bashshellsed

sed find lines with sequential numbers and copy them sorted to new file


I need to get some file content sorted. The file content looks like

...
description of file
http://linktofile/33.txt
description of file
http://linktofile/11.txt
description of file
http://linktofile/22.doc
...

Now I want to cut the entries out and paste them into a new file in correct order so it looks like

description of file
http://linktofile/11.txt
description of file
http://linktofile/22.doc
description of file
http://linktofile/33.txt
...

Is it possible to let sed look for the number in that lines with link and then cut the whole line out into a new file with correct order and also with the respective above file description?


Solution

  • Ok guys thx for your thoughts. I found solution on my own and want to share it with you. Its maybe more like a workaround and fiddly but in the end does what I want.

    Step 1: Delete all newlines and replace them with some indicator so every 2 lines become 1 line

    sed -i 'N;s/\n/ ## /' file
    

    Step 2: On recurring part in every link insert an indicator for sort

    sed -i 's/recurringpart\//recurringpart\/~/g' file
    

    Step 3: Use sort to tidy up the mess.

    sort -t~ -k2 -g -r -o file file
    

    Step 4 : Replace the "newline indicator" with newline so every line gets separated in 2 lines again

    sed -i 's/ ## /\n/g' file
    

    Step 5: Remove the sort indicator

    sed -i 's/recurringpart\/~/recurringpart\//g' file