Search code examples
linuxbashsortingrangelines

Bash - sort range of lines in file


Hi fellow overflow users.

I would love to know how to sort a range of lines in a file through a terminal command in Linux.

For example in a test.sh file:

g++ -o test.out \
Main.cpp \
Framework.cpp \
Sample.cpp \
Blub.cpp \
-std=c++14 -lboost

How do I sort from the second line to the second last line (the source file names) in this file.

Desired Output:

g++ -o test.out \
Blub.cpp \
Framework.cpp \
Main.cpp \
Sample.cpp \
-std=c++14 -lboost

(Sorted from line 2 - 5)

Thank you for your attention :)


Solution

  • With head, GNU sed and tail:

    (head -n 1 test.sh; sed -n '2,${/\\/p}' test.sh | sort; tail -n 1 test.sh) > test_new.sh
    

    Output:

    g++ -o test.out \
    Blub.cpp \
    Framework.cpp \
    Main.cpp \
    Sample.cpp \
    -std=c++14 -lboost