Issue
I am trying to grep for the delimiters (comma or pipe or semicolon) in the multiple files.
If the file contains any of these delimiters then it is fine. I want to move files that don't contain any of these delimiters to the mvfiles
directory. The script is currently moving all the files even if the delimiters exist in the files.
filename=$(find /opt/interfaces/sample_check -type f \( -name "*message.txt*" -or -name "*comma2*" -or -name "*comma3*" \))
pathname=/opt/interfaces/sample_check
echo $filename
echo $pathname
if `head -1 $filename | grep -o [';']`; then
echo "Found"
else
mv $filename /opt/interfaces/sample_check/mvfiles
fi
Solution
Try adjusting your logic a little. Also, include all your delimiters in your grep pattern, and tweak where you put your quotes for it.
pathname=/opt/interfaces/sample_check
find "$pathname" -type f \( -name "*message.txt*" -or -name "*comma[23]*" \) |
while read -r filename
do if sed -n '1d; 2{ /[,;|]/q0 }; q1' "$filename"
then echo "Delimited: $filename"
else echo "Moving ==>> $filename"
mv "$filename" /opt/interfaces/sample_check/mvfiles/
fi
done
Since we only want to decide based on delimiters in line 2 of the file, let's use sed
instead.
sed -n '1d; 2{/[,;|]/q0 }; q1'
sed -n
says print nothing unless requested - we don't need any output.
1d
deletes the first line (we're not editing, just abandoning any further processing on this line so it skips the rest of the program.)
2{...}
says do these commands only on line 2. /[,;|]/q0
says if the line has any comma, semicolon, or pipe, then quit with a zeo exit code to indicate success.
q1
says if it gets here, quit with exit code of 1.
These trigger the branching of the if
. :)
Answered By - Paul Hodges