5

I have a script to sort respect to certain column in a for loop. I would like to skip the header in the sorting process but I'm failing. This is what I have:

for i in file* 
do
  sort -k 1,1 -k 3,3n -t\; ${i} > h${i}
  rm ${i}
done

How to skip the the header in the sorting process but keep it in the output?

Thanks.

1
  • 1
    All the curly braces are superfluous since there's no ambiguity to be avoided. Far more important would be to quote the variables: "$i" Commented Jun 29, 2012 at 8:47

6 Answers 6

8
cat YOURFILE| (read -r; printf "%s\n" "$REPLY"; sort)
Sign up to request clarification or add additional context in comments.

2 Comments

Any reason for the raw flag ? the printf instead of just echo "$REPLY" ? I guess it's just to escape or avoid escaping characters, but a little explaining would be welcome. Otherwise clearly the most elegant solution to pipe the data.
This one is almost perfect but you need to use "IFS= read" instead of "read" to keep leading and trailing spaces.
3

Is header the first line of the file? If it is, try next one:

for i in file* 
do
  head -1 ${i} > h${i}
  sed 1d ${i} | sort -k 1,1 -k 3,3n -t\; >> h${i}
  rm ${i}
done

1 Comment

This works fine for me. The important think to keep in mind is the head -1 ${i} > h${i} line which actually save the header before it is removed and the file sorted. This is what I was missing.
1
$ netstat -nt | (sed -u 2q; sort -k4,4V)
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:22            127.0.0.1:54088         ESTABLISHED
tcp        0      0 127.0.0.1:22            127.0.0.1:54096         ESTABLISHED
tcp        0      0 127.0.0.1:900           172.17.0.4:39452        TIME_WAIT
tcp        0      0 127.0.0.1:900           172.17.0.4:39468        TIME_WAIT

Comments

0

You can remove the header before sorting using sed. untested code.

for i in file* 
do
  sed 1d ${i} | sort -k 1,1 -k 3,3n -t\; > h${i}
  rm ${i}
done

2 Comments

Is that ${1} or ${i}? in line 3
This will output just the header since the sed command will automatically generate an empty file. So at the end you get just the header.
0

This might work for you (GNU sed and Bash):

sed -i '1{h;d};:a;$!{N;ba};s/.*/cat <<\\EOF|sort -k1,1 -k3,3n -t\\;\n&\nEOF/e;H;g' file*

Comments

0
for i in file* 
do
    awk 'NR==1;NR>1{print|"sort  -k 1,1 -k 3,3n -t\;"}' ${i} > $h{i} 
    rm ${i}
done

Comments