我试图在一组unix2dos源代码文件上使用C++。基本上,unix2dos将LF转换为CRLF。
我只需做以下几件事,它就能做我想做的事:
#!/bin/sh
find . -type f \( -name "*.h" -o -name "*.cpp" \) -exec unix2dos {}\;但我不希望文件被修改,如果它已经有CRLF结束行。这就是为什么我必须修改脚本。
#!/bin/sh
for i in `find . -type f \( -name "*.h" -o -name "*.cpp" \)`
do
LINE=`file $i | grep CRLF`
if [ $? -eq 1 ]
then
unix2dos $i
fi
done使用for循环似乎有点棘手,因为空间没有被正确处理。当文件名包含空格时,shell试图不正确地将unix2dos应用于拆分的字符串。
我该如何解决这个问题?
发布于 2013-12-13 09:25:33
只需使用以下内容更改您的unix2dos命令(由putnamhill上方提供):
`perl -wpi -e 's/([^\r])\n/$1\r\n/g' $1`;然后执行前面的find命令:
#!/bin/sh
find . -type f \( -name "*.h" -o -name "*.cpp" \) -exec unix2dos {}\;你们都准备好了。
发布于 2013-12-12 17:06:00
您可以使用以下perl,这将使CRLF文件保持不变:
#!/bin/sh
find . -type f \( -name "*.h" -o -name "*.cpp" \) -exec perl -pi -e 's/([^\r])\n/$1\r\n/' "{}"\;它将在没有CR前面的任何LF之前插入一个CR。
发布于 2013-12-12 16:45:37
尝试下面的代码:
#!/bin/sh
find . -type f \( -name "*.h" -o -name "*.cpp" \) | while read i
do
LINE=`file "$i" | grep -c CRLF`
if [ $LINE -eq 0 ]
then
unix2dos "$i"
fi
done更新:,如果您决定使用BASH,那么您可以更有效地执行这个循环。考虑以下代码:
#!/bin/bash
while read file
do
grep -q $'\r'"$" "$file" && unix2dos "$file"
done < <(find . -type f \( -name "*.h" -o -name "*.cpp" \))< <(...)语法称为process substitution,它在当前shell本身中创建了while循环,从而允许您在当前shell进程中设置shel变量,并保存子shell创建的分叉。
https://stackoverflow.com/questions/20549131
复制相似问题