help-bash
[Top][All Lists]
Advanced

[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: Greg Wooledge
Subject: Re: [Help-bash] Is there a way to read the first empty field in a TSV input?
Date: Thu, 28 Sep 2017 12:05:10 -0400
User-agent: NeoMutt/20170113 (1.7.2)

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.

For example:

IFS=$'\005' read -r a b c < <(tr $'\t' $'\005' <<< $'\tx\ty')

Here, I arbitrarily chose ASCII character 0x05 as the new separator,
on the assumption that it cannot appear in your data.  Use tr to
convert all the tabs to 0x05 upon input, and set IFS to that char.

If your data has no "safe" characters like 0x05 or DEL that you can
use as a separator, then there are other scripting languages.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]