bash 从bash中的文件读取的行中删除换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24159287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
removing linebreak from a line read from a file in bash
提问by user3304726
I have a file containing some lines. I wanted to store each line to a variable , but the line must be chomped (the way its done in perl - chomp($Line) ) in shell script.
我有一个包含一些行的文件。我想将每一行存储到一个变量中,但该行必须在 shell 脚本中被 chomped(在 perl 中完成的方式 - chomp($Line) )。
The code containing the functionality of opening a file and reading the lines is
包含打开文件和读取行的功能的代码是
p_file() {
File=
count=0
while read LINE
do
chomped_line=$LINE **#How to delete the linebreaks**
echo $chomped_line
done < $File
}
How to delete the linebreaks and store the string in the variable(chomped_line) as above
如何删除换行符并将字符串存储在变量(chomped_line)中,如上
回答by konsolebox
Simply use
只需使用
while IFS=$' \t\n\r' read -r LINE
It would exclude leading and trailing spaces even carriage returns characters (\r
) every line. No need to chomp it.
它会排除前导和尾随空格,甚至\r
每行回车符 ( )。没必要咬它。
If you still want to include other spaces besides \n
and/or \r
, just don't specify the others:
如果您还想包含除\n
and/or之外的其他空格\r
,请不要指定其他空格:
while IFS=$'\n\r' read -r LINE
Another way if you don't like using IFS is just to trim out \r
:
如果您不喜欢使用 IFS,另一种方法就是修剪\r
:
chomped_line=${LINE%$'\r'}
* -r
prevents backslashes to escape any characters.
* -r
防止反斜杠转义任何字符。