我有大量以某种方式缩进的文件,并希望将它们转换为不同的缩进样式(它们缩进了 4 个空格,我希望它们使用 2 个空格)。如何自动调整大量文件的缩进(最好给出文件列表,因为只有具有特定扩展名的文件才有此标签大小)。
我使用的是 Windows,但可以访问 Linux 机器并安装了 Cygwin。
对于它的价值,我有非常干净和一致的缩进。但是,这并不像用 2 替换 4 个空格那么简单,因为我们只想替换前导空格。
我能想到的使用unexpandand的最简单方法expand,根据您使用的系统,以下命令(在 Arch Linux 中有效)可能会也可能不会起作用(此命令在 OS X 和 Arch Linux 中具有不同的参数集。请参阅您自己的man unexpand以及man expand详细用法。),
unexpand -t 4 --first-only [your_file] > [temp]
expand -i -t 2 [temp] > [output]
Run Code Online (Sandbox Code Playgroud)
第一个命令所做的是将所有前导 4 空格缩进替换[your_file]为制表符,结果保存为[temp]. 第二个命令将所有前导制表符替换[temp]为 2 个空格组,输出为[output].
当然,您也可以将其管道化为较短的形式
unexpand --first-only -t 4 [your_file] | expand -i -t 2 > [output]
Run Code Online (Sandbox Code Playgroud)
要更改大量文件的缩进,您可以编写一个小脚本文件, example.sh
FILES=/path/to/*.[your_suffix]
OLD_LENGTH=4 # old indentation length
NEW_LENGTH=2 # new indentation length
for f in $FILES; do
unexpand --first-only -t $OLD_LENGTH f | expand -i -t $NEW_LENGTH > f
done
Run Code Online (Sandbox Code Playgroud)
通过调用
sh ./example.sh
Run Code Online (Sandbox Code Playgroud)
您将更改所有满足/path/to/*.[your_suffix].
下面一行:
perl -ne '$_ =~ s|^(( )+)|" " x (length($1)/4)|eg; print $_' < test.txt
Run Code Online (Sandbox Code Playgroud)
将 4 空格缩进替换为 2 空格缩进。
(您可以通过替换来验证" "以"-+"查看生成的模式)
现在,我们可以创建一个 bash 文件,我们将其命名为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"
Run Code Online (Sandbox Code Playgroud)
将要处理的文件列表转储到一个文件中,并执行上面的脚本。原始文件仍然存在,并附加了后缀.orig。因此,例如:
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
Run Code Online (Sandbox Code Playgroud)
您可以通过执行以下操作轻松检查processing.log是否有失败egrep -v '^Success' processing.log。
PS:我在 Cygwin 安装上测试了单行脚本(但不是 bash 脚本);我不记得是perl原始安装的一部分,还是后来添加的。但我认为这是原始安装的一部分。
"-+"使用以下文件测试模式:
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
Run Code Online (Sandbox Code Playgroud)
结果是:
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
Run Code Online (Sandbox Code Playgroud)
编辑 2:这是 Perl 单行代码的更通用版本:
perl -ne '$f=" ";$t=" ";$_=~s|^(($f)+)|$t x (length($1)/length($f))|eg; print $_' < test.txt
Run Code Online (Sandbox Code Playgroud)
$f在此版本中,只需根据需要编辑和 的定义即可$t。
| 归档时间: |
|
| 查看次数: |
1732 次 |
| 最近记录: |