Special variable IFS in shell

Source: Internet
Author: User

Special variable IFS in shell

As I get used to the writing style of python, I often want to use bash to traverse the lines of a file and process the lines read.

But in a strange situation, if my text is similar to this

The first line.
The second line.
The third line.

 

For line in 'cat filename' doecho $ linedone

When I traverse each row of the file through the above method, I find that the read data is as follows:

The
First
Line.
The
Second
Line.
The
Third
Line.

It is obvious that bash does not use line breaks as the separator for a line, but uses spaces as the separator. Of course this is not the expected result, and I cannot explain it.

Until one day I happened to see a shell system variable, IFS.

With regard to FS, awk is always familiar, and awk has four variables that can define separators: RS, ORS, FS, and OFS. The IFS in shell is also used to define separators.

To achieve the desired effect, you only need to assign the IFS value as a separator. However, here we are more specific, so it raises a question.

 

IFS = '\ n' IFS = $ "\ n" IFS = $' \ N'
These three assignments all look like "assigning linefeeds to IFS", but in fact only the last one is what I want.

 

IFS = '\ n' // use the CHARACTER n as the IFS line break.

IFS = $ "\ n" // here \ n is indeed converted to a line break through $, but it is converted to a line break only when it is interpreted (or executed.

IFS = $ '\ n' // This is the real line break.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.