Ημερήσια αρχεία: 30 Αυγούστου 2016


NotePad++: Replace all content after delimiter on each line

We have a configuration file for Skype, that on each line it describes the translation for each element of Skype.

The format on each line is as VARIABLE=VALUE.

We decided to remove all values automatically, to do that we used NotePad++.

Skype - Language File - Dialog

We pressed Ctrl+H to open up the Replace dialog. In the ‘Find what’ field we wrote =[^\n]*$ and in the ‘Replace with’ we wrote =. In the ‘Search Mode’ option we selected ‘Regular expression’.

The tool looked as follows:
Skype - Language File - Before

Hitting the ‘Replace All’ button, removed all values from each line as it can be viewed below:
Skype - Language File - After
=[^\n]*$ instructs NotePad++ to match everything including the = symbol until the end of the line. [^\n]* means to match everything except the new line character. $ matches the end of the line.


Bash: Check if file is found and contains data

The following code will check if the file described by variable FILENAME exists and has data.

if [ ! -f "$FILENAME" ]; then

    echo "Error: '$FILENAME' file not found.";
else

    if [ ! -s "$FILENAME" ]; then

        echo "Error: '$FILENAME' file is empty.";
    else

        echo "Info: '$FILENAME' file found and contains data.";
    fi
fi

Convert a list of integers from MySQL to a Bash array

The following code will connect to a MySQL server, it will get a list of integers and convert the results to a bash array that will be iterated using a for loop and they will be printed using zero padding.


IDS_RAW=$(mysql --user="myuser" --password="mypass" --host="db.example.com" --database="mydb" --batch --compress --skip-column-names --execute="
  SELECT
    Id
  FROM
    Users
  WHERE
    Status = 0;
");

OLDIFS=$IFS;
IFS=$'\n' command eval;
'IDS=($IDS_RAW)';
IFS=$OLDIFS;

echo "Will process the following user IDs '${IDS[@]}'";

for ID in "${IDS[@]}"; do
  LEADING_ZERO=$(printf %08d $ID);
  echo "ID $LEADING_ZERO";
done;

Bash: Get date N days ago in the format YYYY_MM_DD

DEFAULT_DAYS_BACK="0";
DAYS_BACK=${1:-$DEFAULT_DAYS_BACK};
PROCESSING_DATE=`date --date="$DAYS_BACK day ago" +%Y_%m_%d`;

The above code will populate variable PROCESSING_DATE with the date of the day the was DAYS_BACK ago using the format YYYY_MM_DD.

The value for DAYS_BACK is filled by the first argument of the script/function $1. In case the user did not provide an argument, we have the variable DEFAULT_DAYS_BACK that will be used as the default value.