Sunday, September 30, 2012

Awk - separate last field with spaces


Each line of following file 'file.txt' actually has total 4 fields/columns. As you can see some of the values of the last field (4th field, header : Description) has spaces in them.
$ cat file.txt 
ID Name Active Description
2312 DEMO-1 1 Demo for VOD LIVE
1245 DEMO-4 1 LIVE
1002 CUST2 0 VOD Event
19000 DEMO-2 1 VOD
189 DEMO-3 1 Demo for LIVE
Required output:
We need to separate the 4 fields with a comma (,) delimiter such that all the values after 3rd field is considered as 4th field/column. i.e. Required output is something like this:
ID, Name, Active, Description
2312, DEMO-1, 1, Demo for VOD LIVE
1245, DEMO-4, 1, LIVE
1002, CUST2, 0, VOD Event
19000, DEMO-2, 1, VOD
189, DEMO-3, 1, Demo for LIVE
One way to achieve this is to add comma (,) to each of the first 3 fields of every line/row.
$ awk ' { for ( i=1;i<=3;i++ ) {$i=$i","} print }' file.txt
Output:
ID, Name, Active, Description
2312, DEMO-1, 1, Demo for VOD LIVE
1245, DEMO-4, 1, LIVE
1002, CUST2, 0, VOD Event
19000, DEMO-2, 1, VOD
189, DEMO-3, 1, Demo for LIVE
Any other alternative ? Feel free to post in the comment section, much appreciated. Thanks.

And to print the last field of the above input file one solution using UNIX cut command:
$ cut -d" " -f4- file.txt
Output:
Description
Demo for VOD LIVE
LIVE
VOD Event
VOD
Demo for LIVE
Related posts:
- Awk change field separator or delimiter of a file
- UNIX sort file based on last field
- Different ways to print last field of line in UNIX command line

4 comments:

Anirudh said...

sed -e 's/ /,/3;s//,/2;s//,/'

Karan Bohra said...

perl -lpe ' $_ = join ",", split /\s+/, $_, 3+1 ' file.txt

Karan Bohra said...

Required output:
We need to separate the 4 fields with a comma (,) delimiter such that all the values after 3rd field is considered as 4th field/column.

sed -e '
s/ /&\n/3
:loop
s/ \(.*\n\)/,\1/
tloop
s/\n//

' file.txt

Karan Bohra said...

while read -r f1 f2 f3 last
do
set -- "$f1" "$f2" "$f3"
printf '%s, ' "$@"; printf '%s\n' "$last"
done < file.txt

© Jadu Saikia www.UNIXCL.com