Sort strings in CSV according to and without numbers

I have a 4-column CSV file. I want to sort the rows so that rows containing any number somewhere in the third column are placed at the end of the document, rows with numbers in the third column are placed at the beginning. How can I sort the file this way?

Update:

To clarify, I need to move rows containing any number (e.g., a match for [0-9]) somewhere inside the letters of the third column (the third column of the row may contain other characters). Spaces are not important. For instance.

dog, eats chicken, has 4 legs, does not like cats
cat, eats mice, has a tail, does not like water
mouse, eats bugs, has 4 legs, does not like cats
elephant, eats peanuts, has a trunk, does not like mice

Will be sorted by address:

cat, eats mice, has a tail, does not like water
elephant, eats peanuts, has a trunk, does not like mice
dog, eats chicken, has 4 legs, does not like cats
mouse, eats bugs, has 4 legs, does not like cats
+5
source share
4 answers

This might work for you:

sed 'h;s/,/\n/2;s/.*\n/0/;s/,.*//;s/[^0-9]//g;G;s/\n/\t/' file | 
sort -k1,1n -k2 | 
cut -f2

Explanation:

  • , 3- ( 0)
  • ,
+2

- :

awk 'BEGIN {FS=","; OFS=","}; {print match($3,/[0-9]/), $0}' <file> | sort | cut -d, -f2-

  • awk, , ( 0, )
  • sort
  • , cut, , awk.
+4

1- awk, , sort

awk -F',' '$3 ~ /[[:digit:]]/{a[$0];next}1; END{for(i in a)print i}' ./infile

  • , 'a'
  • ,
  • After all the lines have been processed, print the lines that we saved in the array 'a'

Output

$ awk -F',' '$3 ~ /[[:digit:]]/{a[$0];next}1; END{for(i in a)print i}' ./infile
cat, eats mice, has a tail, does not like water
elephant, eats peanuts, has a trunk, does not like mice
mouse, eats bugs, has 4 legs, does not like cats
dog, eats chicken, has 4 legs, does not like cats
+3
source

This will support the order in which the lines are processed, as well as the absence of the use of pipes and external commands.

awk -F, '
$3~/[0-9]+/{a[++i]=$0;x=i;next}1
END{for(i=1;i<=x;i++) print a[i]}' file

Input file:

[jaypal:~/Temp] cat file
dog, eats chicken, has 4 legs, does not like cats
cat, eats mice, has a tail, does not like water
mouse, eats bugs, has 4 legs, does not like cats
elephant, eats peanuts, has a trunk, does not like mice

Test:

[jaypal:~/Temp] awk -F, '
$3~/[0-9]+/{a[++i]=$0;x=i;next}1
END{for(i=1;i<=x;i++) print a[i]}' file
cat, eats mice, has a tail, does not like water
elephant, eats peanuts, has a trunk, does not like mice
dog, eats chicken, has 4 legs, does not like cats
mouse, eats bugs, has 4 legs, does not like cats
+1
source

All Articles