script convert files using dos2unix [closed]
I want to create a script to monitorize my local folder and every time it receives a file starting with frm*, to convert it using dos2unix.
This script is always running and keeps converting the same files, that are already converted, so I think that might be possible an improvement.
What I have now:
while true
do dos2unix //path_to_folder/frm*
doneAny help? Thanks!
92 Answers
The trick is to check the folder's content at certain intervals, and compare the list of files with the last check. Since only new files need to be converted, files that were already in the list the last time can be skipped.
That is what the script below does. It is in python, but the principle is the same in any language.
What it does:
When the script initiates, it makes a list of files in the directory.
Then, in a loop, every 5 seconds:
- it checks for additional files
- if additional files were found, they will be converted, files that were already there are skipped.
- it sets the last checked file list to be the "new" initial file list.
#!/usr/bin/env python3
import subprocess
import time
directory = "/path/to/your/files"
def current_files(): read = subprocess.check_output(["ls", directory]).decode("utf-8").strip() return [item for item in read.split("\n")]
initial_files = current_files()
while True: update = current_files() for item in update: if (item in initial_files, item.startswith("frm")) == (False, True): subprocess.call(["/bin/bash", "-c", "dos2unix", directory+"/"+item]) initial_files = update time.sleep(5)Copy the script into an empty file, set the path to your folder, save it as convert.py, and run the script in the background by the command:
python3 /path/to/convert.py 5 A fragile way using inotifywait and awk:
#!/bin/bash
DIR="/path/to/folder"
while FILE="$(inotifywait '$DIR' -e close_write --format '%e,%f' | awk -F, '$NF ~ /^frm/{print $NF}')"
do echo $FILE; if [[ -f $FILE ]] then dos2unix "$DIR/$FILE" fi
doneNotes:
You need to install
inotify-tools:sudo apt-get install inotify-toolsThis watches only the
close_writeevent, sodos2unixwould happen after the process that created or modified it closed the file.- You could also watch the directory recursively using the
-roption. inotifywaithas an--excludeoption which accepts POSIX-extended regular expressions, but negating a regex (everything exceptfrm) is complicated, and more easily done inawk.- This will break if filenames contain a comma
,. Pick a delimiter in the--formatstring which is guaranteed not to appear in a filename.