linux - Bash 回显奇怪的行为

标签 linux bash shell newline carriage-return

我编写了一个脚本将 .CSV 更改为 json。

#!/bin/bash

exec 0< example.csv

while IFS=, read name element input decrease
do
   echo "${element}decrease: ${decrease}test"
done

我粘贴在这里的 example.csv

name1,A,11,12
name2,B,13,14

但是输出真的很奇怪......

testrease: 12
testrease: 14

如您所见,test重写AdecreaseBdecrease ,使他们成为 testrease .

我简直不敢相信!!所以我尝试了 exec 0< example.csv ,在 stdin 中输入它们,这次我得到了我想要的

name1,A,11,12
Adecrease: 12test

所以我想 example.csv 中可能有一些字符我看不出是什么导致了这个问题。我用cat -v example.csv

name1,A,11,12^M
name2,B,13,14^M

没什么奇怪的,我就卡在这里了。

我对 shell 脚本非常陌生,所以如果有人能给我一些建议,我会非常兴奋!!

最佳答案

谢谢你,@chepner ! tag wiki在这个愚蠢的问题上又节省了我一个小时。

这是来自 wiki 的解决方案:

Check whether your script or data has DOS style end-of-line characters.

  • Use cat -v yourfile or echo "$yourvariable" | cat -v.

    DOS carriage returns will show up as ^M after each line.

    If you find them, delete them using dos2unix (a.k.a. fromdos) or tr -d '\r'.

关于linux - Bash 回显奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52803080/

相关文章:

javascript - Google Chrome 61.0.3163.79 中的 Canvas 在 Linux 上太慢

bash - 如何检查软件包是否已安装,如果没有安装?

linux - 如何在 shell 脚本中使用美元符号登录密码?

bash - 为每次运行的 bash 脚本维护日志

C++/OpenFST - 查找库和链接时出错

windows - Mercurial:Windows 和 Linux 之间文件名中的非 ASCII 字母问题

linux - 在 64 位 DMD 上编译 32 位

linux - 将文件名作为列添加到 csv 文件中

linux - 如何在 bash shell 脚本中包含文件

bash - s3cmd sync 将错误的文件远程复制到错误的位置