moneyslow.com

shell的文本处理(删除空格,转码,批量改名)

shell技巧

shell技巧

删除空格

#!/bin/bash
find . -type f -name "* *" -print |
while read name; do
na=$(echo $name | tr ' ' '_')
if [[ $name != $na ]]; then
mv "$name" "$na"
fi
done

转为utf8:
#!/bin/bash
#enter input encoding here
FROM_ENCODING="GB18030"
#output encoding(UTF-8)
TO_ENCODING="UTF-8"
#convert
CONVERT=" iconv -c -f   $FROM_ENCODING  -t   $TO_ENCODING"

#loop to convert multiple files 
 for  file  in  `find *dizang* -type f -name \*.js`; do
#enca -L zh_CN -x UTF-8 $file
  filetype=`file -i $file`
  echo $filetype | grep -q 'utf-8'
#if ( echo ${filetype} |grep -q 'unknown-8bit' )
  if  [ $? -ne 0 ]; then
#       echo $filetype
        $CONVERT   "$file"   -o  "${file%.txt}.utf8" && mv -f ${file%.txt}.utf8 $file
filetype=`file -i $file`
echo $filetype
  fi

done
exit 0

# more utf81.sh 
#!/bin/bash
#enter input encoding here
FROM_ENCODING="GB18030"
#output encoding(UTF-8)
TO_ENCODING="UTF-8"
#convert
CONVERT=" iconv  -f   $FROM_ENCODING  -t   $TO_ENCODING"

#loop to convert multiple files 
 for  file  in  `find . -type f -name \*txt`; do
  filetype=`file -i $file`
  echo $filetype
#if ( echo ${filetype} |grep -q 'Non-ISO' )
#       then $CONVERT   "$file"   -o  "${file%.txt}.utf8" && mv -f ${file%.txt}.utf8 $file
#fi

done
exit 0

以下是命令
identify xx.jpeg

直接改文件或目录
rename 's/old/new' file

批量改文件名:
比如替换pic_001 为 001
for file in `find . -type f`
do
newfile=`echo $file | sed 's/pic_//g'`
mv $file $newfile
done

批量去除文件名空格
for loop in `ls -1 | tr ' ' '#'`
do
mv "`echo $loop | sed 's/#/ /g' `" "`echo $loop |sed 's/#//g' `" 2> /dev/null
done

grep 多个条件:
grep -E "word1|word2|word3"   file.txt
Exit mobile version