从bash中的文件读取的行中删除换行符 [英] removing linebreak from a line read from a file in bash
问题描述
我有一个包含一些行的文件.我想将每一行存储到一个变量中,但是必须在shell脚本中将这一行切掉(在perl中完成它的方式-chomp($ Line)).
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.
包含打开文件和读取行的功能的代码为
The code containing the functionality of opening a file and reading the lines is
p_file() {
File=$1
count=0
while read LINE
do
chomped_line=$LINE **#How to delete the linebreaks**
echo $chomped_line
done < $File
}
如何删除换行符并将字符串存储在上述变量(chomped_line)中
How to delete the linebreaks and store the string in the variable(chomped_line) as above
推荐答案
只需使用
while IFS=$' \t\r\n' read -r line
即使每行回车返回字符( \ r
),也将排除前导和尾随空格.无需砍.
It would exclude leading and trailing spaces even carriage returns characters (\r
) every line. No need to chomp it.
如果您仍然想在 \ n
和/或 \ r
之外添加其他空格,则不要指定其他空格:
If you still want to include other spaces besides \n
and/or \r
, just don't specify the others:
while IFS=$'\r\n' read -r line
如果您不喜欢使用IFS,另一种方法是修剪 \ r
:
Another way if you don't like using IFS is just to trim out \r
:
chomped_line=${line%$'\r'}
* -r
防止反斜杠转义任何字符.
* -r
prevents backslashes to escape any characters.
这篇关于从bash中的文件读取的行中删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!