Monday, August 20, 2012

bash file name handling scripts


read file names
 
#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in *
do
  echo "$f"
done
IFS=$SAVEIFS

#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
# set me
FILES=/data/*
for f in $FILES
do
  echo "$f"
done
# restore $IFS
IFS=$SAVEIFS
 
#!/bin/bash

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

for f in `cat /root/movedata.txt`
do
  echo "$f"
  ls -l |grep $f
done

IFS=$SAVEIFS
 
read password file
 
while IFS=: read userName passWord userID groupID geCos homeDir userShell
do
      echo "$userName -> $homeDir"
done < /etc/passwd
 
find command
 
find . -print0 | while read -d $'\0' file
do
  echo -v "$file"
done
  
filearray

#!/bin/bash
DIR="$1"
 
# failsafe - fall back to current directory
[ "$DIR" == "" ] && DIR="."
 
# save and change IFS 
OLDIFS=$IFS
IFS=$'\n'
 
# read all file name into an array
fileArray=($(find $DIR -type f))
 
# restore it 
IFS=$OLDIFS
 
# get length of an array
tLen=${#fileArray[@]}
 
# use for loop read all filenames
for (( i=0; i<${tLen}; i++ ));
do
  echo "${fileArray[$i]}"
done
   
splitlines
 
oldifs="$IFS"
IFS="
"
for line in $(< line-with-spaces-between-fields.txt); do
   ...
done
IFS="$oldifs" 

scoop up list of file using "set" builtin

cd ..; set *.txt; cd ~-
 for f; do
 echo "../$f" "$f"
 done
 
remove unwanted characters in filenames:
 
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
FILES=$1/*
for f in $FILES
do
 #echo "$f"
 FILENAME="${f//[\?%\+]/_}";
 mv -b --strip-trailing-slashes "$f" "$FILENAME"
done
IFS=$SAVEIFS
 
replaces ?, % and + with
 
sql example
 
array=($(mysql –host=192.168.1.2 –user=XXXX –password=XXXX -s -N -e ‘use
 xbmc_video; SELECT c22 FROM movie, files WHERE 
files.idFile=movie.idFile ORDER BY idMovie DESC LIMIT 10;’))
 
array=( "${array[@]// /}" )
 
read names into array, and process

#!/bin/bash
DIR=$HOME/HY_DUMP/
# failsafe - fall back to current directory
#[ "$DIR" == "" ] && DIR="."
# save and change IFS
OLDIFS=$IFS
IFS=$'\n\b'
cd $DIR
# read all file name into an array
fileArray=( * )
# restore it
IFS=$OLDIFS
# get length of an array
tLen=${#fileArray[@]}
echo $tLen
# use for loop read all filenames
for (( i=0; i<${tLen}; i++ ));
do
  echo "${fileArray[$i]}"
done
 
http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html