Script para Trabalhar com Arquivos


link: http://www.cyberciti.biz/faq/bash-loop-over-file/


Fazendo loops com arquivos de um diretório:
#!/bin/bash
FILES=/path/to/*
for f in $FILES
do echo "Processing $f file..."
# take action on each file. $f store current file name
cat $f
done


Selecionando um tipo de arquivo:
#!/bin/bash
# Usage: remove all utility bills pdf file password
shopt -s nullglob
for f in *.pdf
do
echo "Removing password for pdf file - $f"
pdftk "$f" output "output.$f" user_pw "YOURPASSWORD-HERE"
done

Para selecionar o diretório atual do script:
directory=$PWD # use current working directory.

Para substituir parte do nome do arquivo, por exemplo a extensão de arquivo:
link: http://tldp.org/LDP/abs/html/string-manipulation.html
${string/%substring/replacement}
If $substring matches back end of $string, substitute $replacement for $substring.
${filename/%.mpg/.mp4}


#!/bin/bash
path=$PWD/*.mpg
shopt -s nullglob 
for fullfilename in $path
do
filename=${fullfilename/$PWD\/}
echo "Transcoding File $filename to ${filename/%.mpg/.mp4} ..."
# 16:9
ffmpeg -i "$filename" -f mp4 -vcodec mpeg4 -b 400k -qmax 10 -bufsize 10M -g 300 -acodec libfaac -ab 96k -ac 2 -s 320x180 -aspect 16:9 "${filename/%.mpg/.mp4}"
# 4:3
#ffmpeg -i "$filename" -f mp4 -vcodec mpeg4 -b 400k -qmax 10 -bufsize 10M -g 300 -acodec libfaac -ab 96k -ac 2 -s 320x240 -aspect 4:3 "${filename/%.mpg/.mp4}"
done

Link: http://mywiki.wooledge.org/BashPitfalls#for_i_in_.60ls_.2A.mp3.60

Código melhorado (que permite utilizar arquivos com espaços nos nomes e diretórios):
#!/bin/bash
path=*.mpg
shopt -s nullglob 
for filename in $path
do
echo "Transcoding File $filename to ${filename/%.mpg/.mp4} ..."
# 16:9
ffmpeg -i "$filename" -f mp4 -vcodec mpeg4 -b 400k -qmax 10 -bufsize 10M -g 300 -acodec libfaac -ab 96k -ac 2 -s 320x180 -aspect 16:9 "${filename/%.mpg/.mp4}"
# 4:3
#ffmpeg -i "$filename" -f mp4 -vcodec mpeg4 -b 400k -qmax 10 -bufsize 10M -g 300 -acodec libfaac -ab 96k -ac 2 -s 320x240 -aspect 4:3 "${filename/%.mpg/.mp4}"
done


Comments