Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active July 25, 2021 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/1daa8771b4e25404ef21bf703ea0b940 to your computer and use it in GitHub Desktop.
Save mtvbrianking/1daa8771b4e25404ef21bf703ea0b940 to your computer and use it in GitHub Desktop.
xmllint indent and file overwrite helpers
# https://stackoverflow.com/a/40190976/2732184
# https://unix.stackexchange.com/a/50202/315380
# https://askubuntu.com/a/222371/575565
file=""
indent=" "
overwrite=0
while [ $# -gt 0 ]
do
unset OPTIND
unset OPTARG
while getopts i:o:w options
do
case $options in
i)
indent="$OPTARG"
# echo "--indent=$indent"
;;
o)
output="$OPTARG"
# echo "--output=$output"
;;
w)
overwrite=1
# echo "--overwrite"
;;
esac
done
shift $((OPTIND-1))
# file="${file} $1"
file="${1:-$file}"
shift
done
# echo "File=$file"
if [ -z "$file" ]; then
echo "No file specified!"
exit 1
fi
if [ ! -z "$output" ]; then
XMLLINT_INDENT="$indent" xmllint "$file" --format -o "$output"
exit 1
fi
if [ "$overwrite" -eq 1 ]; then
# XMLLINT_INDENT="$indent" xmllint "$file" --format > "$file.tmp" && mv "$file.tmp" "$file"
XMLLINT_INDENT="$indent" xmllint "$file" --format --output "$file.tmp" && mv "$file.tmp" "$file"
exit 1
fi
XMLLINT_INDENT="$indent" xmllint "$file" --format
exit 1
@mtvbrianking
Copy link
Author

mtvbrianking commented Jul 25, 2021

Usage

Lint large files

xmltidy users.xml

xmllint users.xml --format

Lint large files

xmltidy users.xml | more

xmllint users.xml --format | more

Set indentation

xmltidy users.xml -i "    "


XMLLINT_INDENT='    ' xmllint users.xml --format

Overwrite

xmltidy users.xml -w

xmllint users.xml --format > users.xml.tmp && mv users.xml.tmp users.xml

Write to new file

xmltidy users.xml -o pretty-users.xml

xmllint users.xml --format --output pretty-users.xml

Prettify specified xml file, 4 space indent 🔥

xmltidy users.xml -w

XMLLINT_INDENT='    ' xmllint users.xml --format > users.xml.tmp && mv users.xml.tmp users.xml

@mtvbrianking
Copy link
Author

mtvbrianking commented Jul 25, 2021

Lint .xml files in a directory

xmltidydir.sh

#! /bin/sh
for file
do
    echo "-> $file"
    # XMLLINT_INDENT="    " xmllint $file --format > $file.tmp && mv $file.tmp $file
    XMLLINT_INDENT="    " xmllint $file --format --output $file.tmp && mv $file.tmp $file
done

Usage

find my-project -type f -name "*.xml" -path "my-project/configs/*" | xargs -- ./path-to/xmltidydir.sh

Source: https://unix.stackexchange.com/a/50202/315380

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment