bash Shell Scripting 不需要'?' 文件名末尾的字符

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

Shell Scripting unwanted '?' character at the end of file name

bashshellcp

提问by premprakash

I get an unwanted '?' at the end of my file name while doing this:

我得到一个不需要的 '?' 在执行此操作时在我的文件名末尾:

emplid=$(grep -a "Student ID" "$i".txt  | sed 's/(Student ID:  //g' | sed 's/)Tj//g' ) 
 #gets emplid by doing a grep from some text file
echo "$emplid"   #prints employee id correctly 
cp "$i" "$emplid".pdf  #getting an extra '?' character after emplid and before .pdf

i.e instead of getting the file name like 123456.pdf , I get 123456?.pdf . Why is this happening if the echo prints correctly? How can I remove trailing question mark characters ?

即,我没有得到像 123456.pdf 这样的文件名,而是得到 123456?.pdf 。如果回声打印正确,为什么会发生这种情况?如何删除尾随的问号字符?

回答by Gordon Davisson

It sounds like your script file has DOS-style line endings (\r\n) instead of unix-style (just \n) -- when a script in this format, the \r gets treated as part of the commands. In this instance, it's getting included in $emplid and therefore in the filename.

听起来您的脚本文件具有 DOS 样式的行结尾 (\r\n) 而不是 unix 样式(只是 \n)——当脚本采用这种格式时,\r 被视为命令的一部分。在这种情况下,它包含在 $emplid 中,因此包含在文件名中。

Many platforms support the dos2unixcommand to convert the file to unix-style line endings. And once it's converted, stick to text editors that support unix-style text files.

许多平台支持dos2unix将文件转换为 unix 样式行尾的命令。一旦它被转换,坚持使用支持 unix 样式文本文件的文本编辑器。

EDIT: I had assumed the problem line endings were in the shell script, but it looks like they're in the input file ("$i".txt) instead. You can use dos2unix on the input file to clean it and/or add a cleaning step to the sed command in your script. BTW, you can have a single instance of sed apply several edits with the -e option:

编辑:我假设问题行结尾在 shell 脚本中,但看起来它们在输入文件 ("$i".txt) 中。您可以在输入文件上使用 dos2unix 来清理它和/或向脚本中的 sed 命令添加清理步骤。顺便说一句,您可以使用 -e 选项让 sed 的单个实例应用多个编辑:

emplid=$(grep -a "Student ID" "$i".txt  | sed '-e s/(Student ID:  //g' -e 's/)Tj//g' -e $'s/\r$//' )

I'd recommend againstusing sed 's/.$//'-- if the file is in unix format, that'll cut off the last character of the filename.

我建议不要使用sed 's/.$//'-- 如果文件是 unix 格式,那将切断文件名的最后一个字符。

回答by user3255079

using the file command to detect if it is pure unix or mixed with DOS.

使用 file 命令来检测它是纯 unix 还是与 DOS 混合。

DOS file: ASCII text, with CRLF line terminators

DOS 文件:ASCII 文本,带有 CRLF 行终止符

Unix file is pure ASCII file.

Unix 文件是纯 ASCII 文件。