7

I have file input.txt with below data in TAB delimited format-

23776112        Inactive        Active
23415312        Inactive        Active

As per requirement, Inside the while loop, I want to use cut 1st column's data and print it -

Below is the part of code-

......
......
    while read line
    do  
        SN=`echo ${line}|cut -d '       ' -f1`
        echo $SN
    done < input.txt
....
....

To use the tab as delimiter above, I am using Ctrl V Tab

But the output is not as expected.I am getting O/P-

23776112 Inactive Active
23415312 Inactive Active

Whereas I want O/P like -

23776112 
23415312
Chris Davies
  • 116,213
  • 16
  • 160
  • 287

3 Answers3

14
cut -f 1 input.txt

This gives you the first column from the tab-delimited file input.txt. The default field delimiter for cut is the tab character, so there's no need to further specify this.

If the delimiter is actually a space, use

cut -d ' ' -f 1 input.txt

If it turns out that there are multiple tabs and/or spaces, use awk:

awk '{ print $1 }' input.txt

The shell loop is not necessary for this operation, regardless of whether you use cut or awk.

See also "Why is using a shell loop to process text considered bad practice?".


The reason your script does not work is because the tab disappears when you echo the unquoted variable.

Related:

Kusalananda
  • 333,661
3

Tab is the default separator for cut, you don't need an explicit argument for it.

However, you need to quote your variable to prevent the tabs from being turned into space.

SN=`echo "${line}"|cut -f1`

But you can also avoid using cut in the first place. Just set IFS to \t.

IFS=$'\t'
while read -r SN rest
do 
    echo "$SN"
done < input.txt
Barmar
  • 9,927
1

bash interprets

$'\t'

as tabulator, so

cut -d $'\t' -f 1

is the way to tell cut to use the tabulator as seperator (which, however, is redunant, as it is default). However, I would prefer awk with the same syntax:

awk -v FS=$'\t' '{ print $1 }' < input.txt
rexkogitans
  • 1,329