echo command do not print the curly braces properly, while running in shell script
本问题已经有最佳答案,请猛点这里访问。
我正在编写一个shell脚本,它读取csv文件并打印读取值:
1 2 3 4 5 6 7 | #!/bin/bash #echo"Starting execution in script" exec < src/main/resources/test1.csv || exit 1 read header # read (and ignore) the first line while IFS=, read name age salary ; do echo "{""name"":""${name}"",""age"":${age},""salary"":${salary}}" done |
test1.csv(输入文件):
1 2 3 4 5 | name,age,salary Subhash,26.0,10000.0 Amit,25.0,20000.0 Rohit,28.0,3000.0 Manoranjan,20.0,50000.0 |
在运行脚本时,我按以下方式获取输出:
1 2 3 4 | }"name":"Subhash","age":26.0,"salary":10000.0 }"name":"Amit","age":25.0,"salary":20000.0 }"name":"Rohit","age":28.0,"salary":3000.0 }"name":"Manoranjan","age":20.0,"salary":50000.0 |
但是,如果我尝试在终端上运行上述脚本中的相同回声线,我将获得带有大括号的正确输出:
1 | {"name":"subhash","age":23,"salary":1000} |
上面的脚本有什么问题?
问题是你的test1.csv包含"windows"
行返回。
将
我不确定为什么交互式地为你工作(你是否以同样的方式读取变量?)但是你只需要清理你的输入文件,或者从最后一个变量的末尾删除它,例如:
'}
(作为旁注,您不需要退出报价来打印转义报价,因此您的回显可能如下所示:
'}}"
)
我稍稍改编了你的剧本; 删除了
1 2 3 | while IFS=, read name age salary; do echo "{""name"":""${name}"",""age"":${age},""salary"":${salary}}" done < <(sed 1d src/main/resources/test1.csv | awk '{$1=$1};1') |