The following one-liner:
perl -ne '$_ =~ s|^(( )+)|" " x (length($1)/4)|eg; print $_' < test.txt
Replaces 4-space indent with 2-space indents.
(You can verify by replacing " "
with "-+"
to see the generated pattern)
Now, we can create a bash file, let's call it indent-changer.sh
:
#!/bin/bash
while read filename; do
if ! [[ -r "$filename" ]]; then
echo "Skipping '$filename' because not readable"
continue
fi
tempfile="$(mktemp)"
if perl -ne '$_ =~ s|^(( )+)|" " x (length($1)/4)|eg; print $_' < "$filename" > "$tempfile"; then
mv "$filename" "$filename".orig
mv "$tempfile" "$filename"
echo "Success processing '$filename'"
else
echo "Failure processing '$filename'"
fi
done < "$1"
Dump the list of files to be processed into a file, and execute the above script. Original file still exist with the suffix .orig
appended. So, for example:
find . -type f -iname "*.txt" > files-to-process.lst
# Verify or edit the .lst file as needed
./indent-changer.sh files-to-process.lst > processing.log
You can check processing.log for failures easily, by doing egrep -v '^Success' processing.log
.
PS: I tested the one-liner (but not the bash script) on my Cygwin installation; I don't remember if perl
is part of original installation, or added afterwards. But I think it's part of original installation.
Testing the "-+"
pattern with the following file:
THis is a test file
With indentation
more indentation
plus internal spaces
outdent
indent again
another internal space example
two spaces after two indents
end
end
end
Results in:
THis is a test file
-+With indentation
-+-+more indentation
-+-+plus internal spaces
-+outdent
-+-+indent again
-+-+another internal space example
-+-+ two spaces after two indents
-+-+end
-+end
end
Edit 2: Here's a more generic version of the Perl one-liner:
perl -ne '$f=" ";$t=" ";$_=~s|^(($f)+)|$t x (length($1)/length($f))|eg; print $_' < test.txt
With this version, simply edit the definitions for $f
and $t
as needed.