i need help using awk. Thanks
i have a file it contains the following
text.txt
The Hunger Games:Suzanne Collins:1:2:3
Weapon X:Stan Lee:3:4:5
the code that i was using to print the lines
awk -F '[:]' '{print $1, $2 ,"$"$3, $4 , $5 }' BookDB.txt
i wish for the out put to become like this
The Hunger Games Suzanne Collins 1 2 3
Weapon X Stan Lee 3 4 5
You can pipe awk output to column
like this:
awk -F ':' -v OFS=':' '{print $1, $2 , $3, $4 , $5}' BookDB.txt | column -s ':' -t
The Hunger Games Suzanne Collins 1 2 3
Weapon X Stan Lee 3 4 5
The output you show is not tab-separated, it's formatted as a table and for that all you need is:
$ column -t -s: file
The Hunger Games Suzanne Collins 1 2 3
Weapon X Stan Lee 3 4 5
If you really wanted it to be tab-separated then that'd be:
$ tr ':' '\t' < file
The Hunger Games Suzanne Collins 1 2 3
Weapon X Stan Lee 3 4 5
If you wanted specific fields:
$ cut -d':' -f 1,4 file | column -t -s:
The Hunger Games 2
Weapon X 4
$ cut -d':' -f 1,4 file | tr ':' '\t'
The Hunger Games 2
Weapon X 4
$ awk -F':' -v OFS='\t' '{print $1, $4}' file
The Hunger Games 2
Weapon X 4
If you don't have column
but want tabular output, you can do it all in awk:
$ cat tst.awk
BEGIN { FS = ":"; ARGV[ARGC] = ARGV[ARGC-1]; ARGC++ }
{
for (i=1; i<=NF; i++)
if (NR==FNR)
width[i] = (length($i) > width[i] ? length($i) : width[i])
else
printf "%-*s%s", width[i], $i, (i<NF?OFS:ORS)
}
$ awk -f tst.awk file
The Hunger Games Suzanne Collins 1 2 3
Weapon X Stan Lee 3 4 5
Try this to get tab spacings as in your example:
awk -F: '{if(NR==2)$2="\t"$2;print $1, $2, $3, $4, $5}' OFS="\t" BookDB.txt
Setting :
as field seperator and \t
as output field seperator. Then for the second line (NR==2)
, add one extra tab
for the second field. Then print the fields.
Or even simpler (if it is acceptable for you):
sed "s/:/\t/g" BookDB.txt