[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Is there a way to read the first empty field in a TSV in
From: |
Evan Gates |
Subject: |
Re: [Help-bash] Is there a way to read the first empty field in a TSV input? |
Date: |
Thu, 28 Sep 2017 09:39:34 -0700 |
User-agent: |
s-nail v14.8.6 |
Greg Wooledge <address@hidden> wrote:
> On Thu, Sep 28, 2017 at 10:56:14AM -0500, Peng Yu wrote:
> > Hi,
> >
> > The following example shows that the variable "a" gets the value of
> > "x" which is the 2nd field of the input. I'd like "a" to always get
> > the first field even it may be empty. Is possible with bash?
> >
> > ~$ IFS=$'\t' read -r a b c <<< $'\t'x$'\t'y
>
> Whitespace characters in IFS are treated differently than non-whitespace
> characters in IFS.
>
> If your input file has whitespace characters as separators but you want
> them to be treated the same way that, say, colons are treated in
> /etc/passwd then you have a couple choices:
>
> 1) Use a language other than bash.
> 2) Convert the separators into some other character that bash treats
> the way you want.
A third option, manually loop. I ran into this recently writing a gopher
client in bash where the separator is tab and all other characters are
allowed IIRC. My solution was:
pack() {
printf '%s\t' "$ft" "$disp" "$sel" "$host" "$port" "$search"
}
unpack() {
local line
IFS= read -r line
for k in ft disp sel host port search; do
printf -v "$k" %s "${line%%$'\t'*}"
line=${line#*$'\t'}
done
}
emg