Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active Jul 25, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@mtvbrianking 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

This comment has been minimized.

Copy link
Owner Author

@mtvbrianking 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