2012-01-24 52 views
5

我试图找到所有具有编码iso-8859-1的文本文件并将它们转换为UTF-8。我尝试到目前为止是:xargs:重定向后的变量替换

find . -name '*.txt' | xargs grep 'iso-8859-1' | cut -d ':' -f1 | 
xargs iconv -f ISO-8859-1 -t UTF-8 {} > {}.converted 

的(明显)的问题是,最后的变量替换将不起作用,因为重定向后发生{},并且不属于xargs。因为我只有一个文件叫做{}.converted,而不是a.txt.convertedb.txt.converted等。我该如何做这项工作?

注意:我在Cygwin上做这个,iconv似乎不支持-o

+0

请看看这个[相关问题](http://stackoverflow.com/q/845863/183066)。 – jcollado

+0

我不知道接受哪个答案。 e.dan和glenn的答案是最实用的,但Ole Oleges是最美观的。 chorobas也相当不错。必须考虑它。 –

回答

1

怎么样for循环,如:

for file in `find . -name '*.txt' | xargs grep 'iso-8859-1' | cut -d ':' -f1`; do 
    iconv -f ISO-8859-1 -t UTF-8 $file > $file.converted 
done 
+0

你的解决方案如何处理文件:'我兄弟的12条记录:列出a-> z.txt'? –

1

只要您没有任何文件的文件名中换行字符,并假设你有GNU发现和xargs的::

find . -name '*.txt' -print0 | 
xargs -0 grep -l 'iso-8859-1' | 
while read -r file; do 
    iconv -f ISO-8859-1 -t UTF-8 "$file" > "$file".converted 
done 

随着grep -l,您不需要管道中的cut命令。

0

你几乎有:

find . -name '*.txt' | xargs grep -i iso-8859-1 | cut -f1 -d: | \ 
xargs -I% echo iconv -f l1 -t utf8 % \> %.utf | bash 
+0

你的解决方案如何处理文件:'我兄弟的12条记录:列出a-> z.txt '? –

0

echo你希望xargs操作的命令是通过管道传递到shell的字符串,并且将克服替换问题。

find . -name '*.txt' | xargs grep 'iso-8859-1' | cut -d ':' -f1 | 
xargs echo "iconv -f ISO-8859-1 -t UTF-8 {} > {}.converted" | bash