Monday, July 23, 2012

Print double quotes in unix Awk


I have already described in one of the earlier posts on how to print string within single quote in Awk print statement. Here is how we can print strings without "double quotes" in Awk.
$ cat file.txt 
6289693505455 Plan_DAIL_30D_AA
6289693505475 Plan_DAIL_30D_AA
6289693505462 Plan_DAIL_30D_AB
Output required:
Plan_DAIL_30D_AA "6289693505455"
Plan_DAIL_30D_AA "6289693505475"
Plan_DAIL_30D_AB "6289693505462"
i.e. Print the first field of the file within "double quotes".
Here are some of the alternatives:
$ awk '{print $2,$1}' file.txt 
Plan_DAIL_30D_AA 6289693505455
Plan_DAIL_30D_AA 6289693505475
Plan_DAIL_30D_AB 6289693505462

$ awk '{print $2,"\""$1"\""}' file.txt 
Plan_DAIL_30D_AA "6289693505455"
Plan_DAIL_30D_AA "6289693505475"
Plan_DAIL_30D_AB "6289693505462"

#Assigning the quotes sequence to a variable x 
$ awk -v x="\"" '{print $2,x$1x}' file.txt 
Plan_DAIL_30D_AA "6289693505455"
Plan_DAIL_30D_AA "6289693505475"
Plan_DAIL_30D_AB "6289693505462"

#Using octal code of double quotes
$ awk '{print $2,"\042"$1"\042"}' file.txt 
Plan_DAIL_30D_AA "6289693505455"
Plan_DAIL_30D_AA "6289693505475"
Plan_DAIL_30D_AB "6289693505462"

#Using ASCII code of double quotes
$ awk '{print $2,"\x22"$1"\x22"}'  file.txt 
Plan_DAIL_30D_AA "6289693505455"
Plan_DAIL_30D_AA "6289693505475"
Plan_DAIL_30D_AB "6289693505462"
Related posts: - Accessing external variable in Awk and Sed

Thursday, July 12, 2012

Unix sort file ignoring first line


Input file:
$ cat file.txt 
chrom:index:forward:reverse
chr01:13:1:2
chr03:12:1:4
chr01:3445:1:6
chr02:2311:3:1
chr13:23432:4:7
chr01:212:5:2
chr02:345:12:6
chr01:45:45:0
Output required:
 
chrom:index:forward:reverse
chr01:13:1:2
chr01:45:45:0
chr01:212:5:2
chr01:3445:1:6
chr02:345:12:6
chr02:2311:3:1
chr03:12:1:4
chr13:23432:4:7
i.e. Sort file.txt ignoring the header line (1st line).
Sort first field in ascending order (string)
Sort second field in ascending order (numeric)
One of the solution would be:
$ head -1 file.txt ; tail -n +2 file.txt | sort -t : -k1,1 -k2,2n
As you can see two commands are combined together to satisfy the output.
i) First part is printing the first line of file.txt
ii) Second part is printing the lines except first line and then sorting the lines based on first field (string) and second field (numeric sort).
Related posts:
- Unix sort file based on last field
- Sort strings by length using Awk
- Unix sort date in ddmmyyyy format using Awk

© Jadu Saikia http://unstableme.blogspot.com