1

I have bunch of files are encoded with GB2312, now I want to convert them into UTF-8, so I apply the code below:

find . | xargs iconv -f GB2312 -t UTF-8

It successfully convert them but the output is printed in console.

Here I want them to be saved in their original files, how do I make it ?

WoooHaaaa
  • 19,732
  • 32
  • 90
  • 138

1 Answers1

1

You could always use a loop instead of xargs. I wouldn't recommend overwriting files in a one-shot command-line call. How about moving them aside first:

for file in `find .`; do
    mv "$file" "$file.old" && iconv -f GB2312 -t UTF-8 < "$file.old" > "$file"
done

Just take care with this. If your file names contain spaces, this loop might not work correctly.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • You code works like a charm, thanks ! Just for curious, is there any one line command to make it ? – WoooHaaaa Jun 24 '13 at 02:47
  • You can put it all on one line if you place a semi-colon after the loop body *ie* `for ...; do mv .... > "$file"; done` – paddy Jun 24 '13 at 02:49
  • By the way, if you have spaces in your filenames, read this: http://stackoverflow.com/questions/7039130/bash-iterate-over-list-of-files-with-spaces – paddy Jun 24 '13 at 02:52
  • 1
    There should be a $ before... ```for file in `find .`; do mv "$file" "$file.old" && iconv -f GB2312 -t UTF-8 < "$file.old" > "$file" done``` This killed one of my code repo sadly. – ProfFan Jun 25 '17 at 12:43