![在 Bash 中用逗号替换反斜杠](https://linux22.com/image/53416/%E5%9C%A8%20Bash%20%E4%B8%AD%E7%94%A8%E9%80%97%E5%8F%B7%E6%9B%BF%E6%8D%A2%E5%8F%8D%E6%96%9C%E6%9D%A0.png)
我尝试编写一个脚本,在其中逐行读取文件。我应该用逗号(,)替换反斜杠(\)。
输入文件如下:
1,2,3,WORKSTATION1\A,5
1,2,3,WORKSTATION2\B,5
1,2,3,WORKSTATION1\C,5
1,2,3,WORKSTATION1\D,5
1,2,3,WORKSTATION1\E,5
1,2,3,WORKSTATION1\F,5
1,2,3,WORKSTATION1\G,5
我写的一段代码如下:
#!/bin/bash
cat $1 | while read -r line
do
ln=$(echo $line | xargs | sed 's/\\/,/g' )
echo $ln
done
echo Done!
当我运行时./script.sh file.csv
,我得到以下输出:
1,2,3,WORKSTATION1A,5
1,2,3,WORKSTATION2B,5
1,2,3,WORKSTATION1C,5
1,2,3,WORKSTATION1D,5
1,2,3,WORKSTATION1E,5
1,2,3,WORKSTATION1F,5
1,2,3,WORKSTATION1G,5
Done!
然而,我期望输出如下:
1,2,3,WORKSTATION1,A,5
1,2,3,WORKSTATION2,B,5
1,2,3,WORKSTATION1,C,5
1,2,3,WORKSTATION1,D,5
1,2,3,WORKSTATION1,E,5
1,2,3,WORKSTATION1,F,5
1,2,3,WORKSTATION1,G,5
Done!
我也尝试sed 's/\\/,/g'
用替换tr "\\" ","
,但没有帮助。需要任何修改吗?
答案1
你试过这个吗
# cat a.txt
1,2,3,WORKSTATION1\A,5
1,2,3,WORKSTATION2\B,5
1,2,3,WORKSTATION1\C,5
1,2,3,WORKSTATION1\D,5
1,2,3,WORKSTATION1\E,5
1,2,3,WORKSTATION1\F,5
1,2,3,WORKSTATION1\G,5
# sed -e 's/\\/,/g' a.txt
1,2,3,WORKSTATION1,A,5
1,2,3,WORKSTATION2,B,5
1,2,3,WORKSTATION1,C,5
1,2,3,WORKSTATION1,D,5
1,2,3,WORKSTATION1,E,5
1,2,3,WORKSTATION1,F,5
1,2,3,WORKSTATION1,G,5
答案2
这是编写您尝试过的相同脚本的更好方法:
#!/bin/bash
while read -r line
do
echo "$line" | sed 's/\\/,/g'
done < "$1"
echo Done!
当然,整个事情可以简化为
#!/bin/bash
tr '\\' , < "$1"
答案3
只要确保你的 shell 在将它们推送到以下位置时不会吃掉这些反斜杠sed
:
sed 's/\\/,/g' <<\BS
1,2,3,WORKSTATION1\A,5
1,2,3,WORKSTATION2\B,5
1,2,3,WORKSTATION1\C,5
1,2,3,WORKSTATION1\D,5
1,2,3,WORKSTATION1\E,5
1,2,3,WORKSTATION1\F,5
1,2,3,WORKSTATION1\G,5
BS
#OUTPUT#
1,2,3,WORKSTATION1,A,5
1,2,3,WORKSTATION2,B,5
1,2,3,WORKSTATION1,C,5
1,2,3,WORKSTATION1,D,5
1,2,3,WORKSTATION1,E,5
1,2,3,WORKSTATION1,F,5
1,2,3,WORKSTATION1,G,5
答案4
这里有一个 awk 解决方案,
$ awk -F'\' '{print $1","$2}' file.txt
1,2,3,WORKSTATION1,A,5
1,2,3,WORKSTATION2,B,5
1,2,3,WORKSTATION1,C,5
1,2,3,WORKSTATION1,D,5
1,2,3,WORKSTATION1,E,5
1,2,3,WORKSTATION1,F,5
1,2,3,WORKSTATION1,G,5