简体   繁体   中英

Only list files; iconv and directories?

I want to convert the coding of some csv-files with iconv . It has to be a script so I am working with while; do done while; do done . The script lists every item in a specific directory and converts them into another coding (utf-8).

Currently, my script lists EVERY item, including directories... So here are my questions

  1. Does iconv has a problem with directories or does it ignore them?

  2. And if there is a problem, how can I only list/search only for files?

I tried How to list only files in Bash? a ***./*** at the beginning of every item and that's kinda annoying (and my program doesn't like it, too).

Another possibility is ls -p | grep -v / ls -p | grep -v / but this would also affect files with / in the name, wouldn't it?

I hope you can help me. Thank you.


Here is the code:

for item in $(ls directory/); do
   FileName=$item
   iconv -f "windows-1252" -t "UTF-8" FileName -o FileName
done

Yea, i know, the input and output file cannot be the same^^

Building upon the existing question that you referenced, Why don't you just remove the first 2 characters ie ./ ?

  find . -maxdepth 1 -type f | cut -c 3-

Edit: I agree with @DevSolar about the space-based problem in the for-loop. While I think that his solution is better for this problem, I just want to give an alternative way to get out of the space-based for-loop issue.

   OLD_IFS=$IFS
   IFS=$'\n'
   for item in $(find . -maxdepth 1 -type f | cut -c 3-); do
   FileName=$item
   iconv -f "windows-1252" -t "UTF-8" FileName -o FileName
   done
   IFS=$OLD_IFS

Use find directly:

find . -maxdepth 1 -type f -exec bash -c 'iconv -f "windows-1252" -t "UTF-8" $1 > $1.converted && mv $1.converted $1' -- {} \;
  • find . -maxdepth 1 -type f find . -maxdepth 1 -type f finds all files in the working directory
  • -exec ... executes a command on each such file (including correct handling of eg spaces or newlines in the filename)
  • bash -c '...' executes the command in '...' in a subshell (easier to do the subsequent steps, involving multiple expansions of the filename, this way)
  • -- terminates option processing, and treats anything after the -- as arguments to the call.
  • {} is replaced by find with the file name(s) found
  • $1 in the bash command is replaced with the first (and only) argument, which is the {} replaced by the filename (see above)
  • \\; tells find where the -exec 'ed command ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM