Using tab delimiter in Cut in Unix Shell Scripting
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:
Why is printf better than echo?
Security implications of forgetting to quote a variable in bash/POSIX shells
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