简体   繁体   English

在Tab中将制表符分隔的字符串拆分为数组

[英]Split tab separated string into array in bash

line="\t\t\t1\t2\t\t3"

What I do: 我所做的:

IFS=$'\t'  DIRS=($line);

What I want to get: 我想得到什么:

DIRS[0]=NULL; DIRS[1]=NULL; DIRS[2]=NULL; DIRS[3]=1;DIRS[4]=2;DIRS[5]=NULL;DIRS[6]=3;

What I actually get: 我实际得到的是:

DIRS[0]=1; DIRS[1]=2; DIRS[2]=3

Is that possible to get what I want to get? 有可能得到我想要的东西吗?

Bash treats whitespace specially in IFS: Bash在IFS中特别对待空格:

If IFS has a value other than the default, then sequences of the whitespace characters space and tab are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). 如果IFS的值不是默认值,则只要单词空格和制表符在IFS值(IFS空格字符)中,该单词的开头和结尾都将被忽略。 Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. IFS中不是IFS空格的任何字符,以及任何相邻的IFS空格字符,都将分隔字段。 A sequence of IFS whitespace characters is also treated as a delimiter. IFS空格字符序列也被视为定界符。

So, use a non-whitespace character. 因此,请使用非空白字符。 (BTW, I use $'\\t' for a tab, search man bash for Quoting ) (顺便说一句,我使用$'\\t'作为标签,搜索man bash 引用

#!/bin/bash
line=$'\t\t\t1\t2\t\t3'

IFS=$':' DIRS=(${line//$'\t'/:})       # Replace tabs with colons.

for (( i=0 ; i<${#DIRS[@]} ; i++ )); do
    echo "$i: [${DIRS[i]}]"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM