IFS word splitting分割字符串

使用find + for in实现so 遍历,发现莫名其妙的问题, 如有的时候字段分割不对, 所以就换成了while + IFS +read

一个例子,现在我们现在要一次读入文件 onefile.txt 的内容并输出,假设文件的内容是这样的:

$ cat ./helloworld.txt
hello world

good job

当我们习惯性地使用 for 循环来解决这个问题时,你会发现输出的结果与预期大相径庭:

首先 helloworld.txt 的内容一次性地输出给 for 循环,然后shell会帮助我们自动断词。用相对形象的 tag 来描述一个空白字符:

hello<blank>world<newline><blank><newline>

这个时候,word splitting 发生了,将以上字符串按照 IFS 分隔成 helloworld, good, job。IFS 是用来分隔命令中的每一个单词的,它可以有多个字符组成,每个字符都被视作分隔符。默认情况下,它的值为 <newline><tab><whitespace,这也是为什么默认都是按空格、回车等空白字符分隔的原因。

这样一来 文本被分隔可以很好地解释,但是那又是为什么第二行的空行没有了呢?原来,当 IFS 包含空白字符时(比如回车、空格、制表符等),在任何需要分隔单词的场景下,位于字符串开头和结尾的空白字符会被删除,另外一点是,字符串中间的连续空白会被压缩成一个。

例如:

$ str=" here is  a    string "
$ echo $str | cat -A
here is a string

那如果我想保留字面值,不想被 IFS 执行分隔,需要怎么做?很简单,加上引号:

$ echo "$str" | cat -A
 here is  a    string$

为了达到我们的目的,可以临时通过设置 IFS 为空,来关闭 word splitting 功能:

$ IFS=
$ for i in $(<onefile.txt); do echo "$i"; done
hello world

$ unset IFS

不过即使你理解了 IFS 的含义,你会发现通过 for 循环来读取文件内容是一件很不靠谱的事,建议使用 while 循环:

$ while IFS= read -r line; do echo "$line" ; done < onefile.txt
hello world

Reference:

http://mywiki.wooledge.org/WordSplitting

 

标签:

About: kiah


15 thoughts on “IFS word splitting分割字符串”

  1. I wanted to send you the very little remark to finally thank you the moment again over the spectacular techniques you have shared above. It’s extremely generous of people like you in giving easily all a few people could have advertised as an e-book in making some bucks for their own end, certainly considering that you could have done it if you considered necessary. The concepts additionally acted as a easy way to be aware that many people have a similar desire just as mine to figure out a great deal more concerning this condition. Certainly there are a lot more enjoyable instances ahead for folks who check out your blog.

  2. I enjoy you because of all of the effort on this blog. Betty delights in carrying out internet research and it’s easy to see why. A lot of people hear all about the compelling form you convey advantageous guidance by means of the blog and attract contribution from other individuals about this area and my child has always been becoming educated a great deal. Enjoy the remaining portion of the new year. You’re carrying out a brilliant job.

  3. I am glad for writing to make you know what a incredible experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the others without hassle thoroughly grasp various tricky topics. You undoubtedly surpassed visitors’ expected results. Thanks for showing those warm and friendly, trustworthy, revealing not to mention unique tips on your topic to Tanya.

  4. I’m also commenting to let you be aware of of the excellent discovery my cousin’s child enjoyed checking your blog. She discovered a wide variety of details, most notably how it is like to have a marvelous coaching heart to get many more effortlessly fully understand certain complicated matters. You actually did more than my desires. I appreciate you for displaying such great, healthy, educational and also cool guidance on that topic to Evelyn.

  5. I am commenting to let you know of the fantastic encounter my cousin’s daughter experienced reading your site. She even learned many issues, not to mention what it’s like to have a wonderful giving mindset to have many people quite simply grasp chosen grueling subject areas. You really exceeded our expectations. Many thanks for giving the informative, healthy, educational and as well as easy thoughts on the topic to Jane.

  6. My wife and i have been really more than happy when Louis managed to finish off his research using the precious recommendations he made through your web site. It is now and again perplexing to simply find yourself making a gift of steps which often some other people may have been trying to sell. Therefore we realize we need the writer to give thanks to for this. The specific illustrations you made, the straightforward web site navigation, the relationships you will help to instill – it is most remarkable, and it is leading our son in addition to us reason why this subject is fun, which is seriously pressing. Thanks for the whole lot!

  7. Thanks for the advice on credit repair on this excellent site. Some tips i would tell people should be to give up the particular mentality that they may buy currently and shell out later. Being a society many of us tend to try this for many issues. This includes vacation trips, furniture, along with items we wish. However, you’ll want to separate your current wants out of the needs. If you are working to boost your credit score actually you need some trade-offs. For example you’ll be able to shop online to save cash or you can look at second hand merchants instead of high-priced department stores pertaining to clothing.

  8. Dzięki za wskazówki dotyczące naprawy kredytu na temat tego wszystkiego blogu. Co ja chciałbym rada ludziom jest zrezygnować z tej mentalności że mogą teraz i zapłać później. As a as be a} społeczeństwo {my|my wszyscy|my wszyscy|wielu z nas|większość z nas|większość ludzi} ma tendencję do {robienia tego|robienia tamtego|próbowania tego|zdarzyć się|powtórz to} dla wielu {rzeczy|problemów|czynników}. Obejmuje to {wakacje|wakacje|wypady|wyjazdy wakacyjne|wycieczki|rodzinne wakacje}, meble, {i|jak również|a także|wraz z|oprócz|plus} przedmiotów {chcemy|chcielibyśmy|życzymy|chcielibyśmy|naprawdę chcielibyśmy to mieć}. Jednak {musisz|musisz|powinieneś|powinieneś chcieć|wskazane jest, aby|musisz} oddzielić {swoje|swoje|to|twoje obecne|swoje|osoby} chcą {od wszystkich|z potrzeb|z}. {Kiedy jesteś|Kiedy jesteś|Kiedy jesteś|Jeśli jesteś|Tak długo, jak jesteś|Kiedy} pracujesz, aby {poprawić swój kredyt|poprawić swoją zdolność kredytową|zwiększyć swój kredyt|zwiększyć swój kredyt|podnieś swój ranking kredytowy|popraw swój kredyt} wynik {musisz zrobić|zrobić|faktycznie potrzebujesz|naprawdę musisz} dokonać kilku {poświęceń|kompromisów}. Na przykład {możesz|możesz|możesz|możesz|będziesz mógł|| możesz|prawdopodobnie możesz} robić zakupy online {aby zaoszczędzić pieniądze|aby zaoszczędzić pieniądze|aby zaoszczędzić} lub {możesz przejść do|może się zwrócić|może odwiedzić|może obejrzeć|może sprawdzić|może kliknąć} używane {sklepy|sklepy|detaliści|sprzedawcy|punkty sprzedaży|dostawcy} zamiast {drogie|drogie|drogie|drogie|drogie|drogich} domów towarowych {dla|w odniesieniu do|dotyczących|odnoszących się do|przeznaczonych dla|do zdobycia} odzieży {termometr bezdotykowy|termometry bezdotykowe|termometry bezdotykowe ranking|termometr do czoła|termometry do czoła|termometr bezkontaktowy|termometry bezkontaktowe|termometr koronawirus|termometr|termometr na podczerwień|termometry na podczerwień|termometr lekarski|termometry lekarskie|szybki termometr medyczny|szybkie termometry medyczne}.

发表评论

电子邮件地址不会被公开。