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.