Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash sort ignore first 5 lines

I'm having trouble ignoring the first 5 lines of my file while sorting the rest. My current command sorts the entire file by the second item, however I need to skip the first 5 "header" lines. I need read it and write it to the same file.

Current Command

sort -f -t $ -k2n,2 -o /folder/File.txt /folder/File.txt

Example

2016/07/07 15:41:02
@24921
@
@
@-1
b$1$4$...
a$2$5$...
like image 595
Austin E Avatar asked Jul 07 '16 22:07

Austin E


2 Answers

This sorts lines 6 and after of the file while leaving the first 5 lines unchanged:

{ head -n5 file.txt; tail -n+6 file.txt | sort -ft$ -k2n,2; } >file.tmp && mv file.tmp file.txt

tcsh

Unlike bash, ksh, and zsh, tcsh does not support command grouping with {...}. Instead try a subshell:

( head -n5 file.txt; tail -n+6 file.txt | sort -ft$ -k2n,2 ) >file.tmp && mv file.tmp file.txt
like image 76
John1024 Avatar answered Sep 21 '22 21:09

John1024


Solution:

  1. Extract the first five lines and the rest into two separate files, head.tmp and tail.tmp.
  2. Sort tail.tmp and concatenate head.tmp with the sorted result.

At the prompt:

$ sed -n -e '1,5w head.tmp' -e '6,$w tail.tmp' data.in
$ sort tail.tmp | cat head.tmp - >data.new
like image 43
Kusalananda Avatar answered Sep 21 '22 21:09

Kusalananda