我何时在Bash中将IFS设置为换行符? [英] When do I set IFS to a newline in Bash?

查看:433
本文介绍了我何时在Bash中将IFS设置为换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为将IFS设置为$'\n'可以帮助我将整个文件读入数组,如下所示:

I thought setting IFS to $'\n' would help me in reading an entire file into an array, as in:

IFS=$'\n' read -r -a array < file

但是,以上命令仅将文件的第一行读入数组的第一元素,而没有其他内容.

However, the above command only reads the first line of the file into the first element of the array, and nothing else.

即使这仅读取数组的第一行:

Even this reads only the first line into the array:

string=$'one\ntwo\nthree'
IFS=$'\n' read -r -a array <<< "$string"

我在该网站上碰到过其他帖子,它们谈论使用mapfile -tread循环将文件读入数组的情况.

I came across other posts on this site that talk about either using mapfile -t or a read loop to read a file into an array.

现在我的问题是:我什么时候完全使用IFS=$'\n'?

Now my question is: when do I use IFS=$'\n' at all?

推荐答案

您的第二次尝试几乎可行,但是您必须告诉read它不仅应该读到换行符(默认行为),而且还应该读到直到空字符串:

Your second try almost works, but you have to tell read that it should not just read until newline (the default behaviour), but for example until the null string:

$ IFS=$'\n' read -a arr -d '' <<< $'a b c\nd e f\ng h i'
$ declare -p arr
declare -a arr='([0]="a b c" [1]="d e f" [2]="g h i")'

但是正如您所指出的,mapfile/readarray是您拥有的方法(需要Bash 4.0或更高版本):

But as you pointed out, mapfile/readarray is the way to go if you have it (requires Bash 4.0 or newer):

$ mapfile -t arr <<< $'a b c\nd e f\ng h i'
$ declare -p arr
declare -a arr='([0]="a b c" [1]="d e f" [2]="g h i")'

-t选项从每个元素中删除换行符.

The -t option removes the newlines from each element.

关于何时要使用IFS=$'\n':

  • 如刚刚所示,如果您想将文件读取到数组中,并且Bash早于4.0,并且不想使用循环,则每个元素仅一行一行
  • 有些人使用IFS进行宣传,但没有空格避免分词带来的意外副作用;我认为,正确的方法是理解单词拆分,并确保根据需要使用适当的引号避免出现这种情况.
  • 我已经看到IFS=$'\n'用于制表符完成脚本,例如
  • As just shown, if you want to read a files into an array, one line per element, if your Bash is older than 4.0, and you don't want to use a loop
  • Some people promote using an IFS without a space to avoid unexpected side effects from word splitting; the proper approach in my opinion, though, is to understand word splitting and make sure to avoid it with proper quoting as desired.
  • I've seen IFS=$'\n' used in tab completion scripts, for example the one for cd in bash-completion: this script fiddles with paths and replaces colons with newlines, to then split them up using that IFS.

这篇关于我何时在Bash中将IFS设置为换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆