bash 读取文本文件时删除 CR (\r)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11734187/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:54:47  来源:igfitidea点击:

Remove CR (\r) while reading text file

bash

提问by user1564015

I have this script where I'm reading a text file line by line and executing a command. I found that the strings (aka lines) always ends with '\r'.

我有这个脚本,我正在逐行读取文本文件并执行命令。我发现字符串(又名行)总是以'\r'.

I wanna remove the CR from the end of the string.

我想从字符串的末尾删除 CR。

This is how my code looks like:

这是我的代码的样子:

file="myfilelist.txt"

while IFS= read -r filename
do

git log --oneline -- ${filename} |wc -l

done <"$file"

I wanna be able to perform the command in the loop without \rat the end of every line string (aka filename).

我希望能够在循环中执行命令而无需\r在每行字符串(又名文件名)的末尾。

回答by Keith Thompson

Try this:

尝试这个:

git log --oneline -- $(echo "$filename" | tr -d '\r') | wc -l

Note that you don't need the curly braces when $filenameis surrounded by whitespace.

请注意,当$filename被空格包围时,您不需要花括号。

In principle you can also do this via bash's own parameter expansion mechanism:

原则上你也可以通过 bash 自己的参数扩展机制来做到这一点:

git log --oneline -- ${filename%^M} | wc -l

but the ^Mhas to be a literal control-M character, which is ugly and difficult to maintain.

但 the^M必须是字面的 control-M 字符,这很丑陋且难以维护。

Or you can delete all whitespace characters at the end of the name (which includes ^Mas well as space, tab, et al):

或者您可以删除名称末尾的所有空白字符(包括^M空格、制表符等):

git log --oneline -- ${filename%[-[:space:]]} | wc -l

But now we're getting into techniques that very few people are likely to recognize without reading the manual.

但是现在我们正在研究一些技术,如果不阅读手册,很少有人可能会认出这些技术