Reading file line by line (with space) in Unix Shell scripting - Issue

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

I want to read a file line by line in Unix shell scripting. Line can contain leading and trailing spaces and i want to read those spaces also in the line. I tried with "while read line" but read command is removing space characters from line :( Example if line in file are:-

abcd efghijk  abcdefg hijk 

line should be read as:- 1) "abcd efghijk" 2) " abcdefg hijk"

What I tried is this (which not worked):-

while read line do    echo $line done 

I want line including space and tab characters in it. Please suggest a way.

回答1:

Try this,

IFS='' while read line do echo $line done 

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word splitting after expansion and to split lines into words with  the  read  builtin  command. The default value is ``'' 


回答2:

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do    printf "\n" "$line" done 

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do    printf "%s\n" "$line" done 

This now is an equivalent of cat as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!