Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK move lines of a file down

Status
Not open for further replies.

judkil

Technical User
Mar 23, 2020
9
FR
Hello,

I own
input
Code:
AB-0004 XXX XXX
A8-0005 XXX
AB-0007 XXX XXX
AB-0008 XXX


and I would like to get

Output
Code:
AB-0004 XXX XXX
AB-0007 XXX XXX
A8-0005 XXX
AB-0008 XXX


I would like to be able to move lines of a file down according to the number of columns whether with an awk or a sed but without relying on the line number

If anyone had an idea! Thank you very much !
 
My only idea is, that you can read all lines into an array and in the END{} print the array elements in order you need
 
You can use awk with sort and cut:

For example we have this file:
Code:
$ cat judkil_sortfile.txt 
AB-0004 XXX XXX
A8-0005 XXX
A8-0006 XXX XXX XXX
AB-0007 XXX XXX
AB-0008 XXX
and we want to sort the lines according to the number of columns.

First, we can use awk to print number of columns (NF = Number of Fields) in every line as the the 1st column
Code:
$ awk '{print NF, $0}' judkil_sortfile.txt
3 AB-0004 XXX XXX
2 A8-0005 XXX
4 A8-0006 XXX XXX XXX
3 AB-0007 XXX XXX
2 AB-0008 XXX

Then, we can use sort, to sort awk's output according to the 1st column in reverse order
Code:
$ awk '{print NF, $0}' judkil_sortfile.txt | sort -nr
4 A8-0006 XXX XXX XXX
3 AB-0007 XXX XXX
3 AB-0004 XXX XXX
2 AB-0008 XXX
2 A8-0005 XXX

Finally, we can use cut, to select from sort's output only the second through last columns (fields)
Code:
$ awk '{print NF, $0}' judkil_sortfile.txt | sort -nr | cut -f2- -d' '
A8-0006 XXX XXX XXX
AB-0007 XXX XXX
AB-0004 XXX XXX
AB-0008 XXX
A8-0005 XXX
.. and that seems to be what you need
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top