Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab separated values in awk

Tags:

awk

How do I select the first column from the TAB separated string?

# echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -F'\t' '{print $1}' 

The above will return the entire line and not just "LOAD_SETTLED" as expected.

Update:

I need to change the third column in the tab separated values. The following does not work.

echo $line | awk 'BEGIN { -v var="$mycol_new" FS = "[ \t]+" } ; { print $1 $2 var $4 $5 $6 $7 $8 $9 }' >> /pdump/temp.txt 

This however works as expected if the separator is comma instead of tab.

echo $line | awk -v var="$mycol_new" -F'\t' '{print $1 "," $2 "," var "," $4 "," $5 "," $6 "," $7 "," $8 "," $9 "}' >> /pdump/temp.txt 
like image 870
shantanuo Avatar asked Mar 21 '11 05:03

shantanuo


People also ask

How do you give tab space in awk?

To place the space between the arguments, just add " " , e.g. awk {'print $5" "$1'} .

How do I change my awk delimiter?

Just put your desired field separator with the -F option in the AWK command and the column number you want to print segregated as per your mentioned field separator.

What is FS and OFS in awk?

FS - Field Separator. NF - Number of Fields. NF - Number of Fields. NR - Total Number of Records. OFS - Output Field Separator.

What is the symbol for tab delimiter?

\t is replaced by an actual tab character (ASCII 0x09 , or Char(9) ) when it's used as a delimiter in your first example. In the second, it's not being replaced, and it's being used as the literal character sequence \ and t .


1 Answers

You need to set the OFS variable (output field separator) to be a tab:

echo "$line" |  awk -v var="$mycol_new" -F'\t' 'BEGIN {OFS = FS} {$3 = var; print}' 

(make sure you quote the $line variable in the echo statement)

like image 63
glenn jackman Avatar answered Sep 21 '22 13:09

glenn jackman