如何在Linux中将给定文本文件中的空格替换为制表符?
UNEXPAND(1) User Commands UNEXPAND(1)
NAME
unexpand - convert spaces to tabs
SYNOPSIS
unexpand [OPTION]... [FILE]...
DESCRIPTION
Convert blanks in each FILE to tabs, writing to standard output. With
no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options
too.
-a, --all
convert all blanks, instead of just initial blanks
--first-only
convert only leading sequences of blanks (overrides -a)
-t, --tabs=N
have tabs N characters apart instead of 8 (enables -a)
-t, --tabs=LIST
use comma separated LIST of tab positions (enables -a)
--help display this help and exit
--version
output version information and exit
. . .
STANDARDS
The expand and unexpand utilities conform to IEEE Std 1003.1-2001
(``POSIX.1'').
我认为你可以尝试使用awk
awk -v OFS="\t" '$1=$1' file1
sed 's/[:blank:]+/,/g' thefile.txt > the_modified_copy.txt
tr -s '\t' < thefile.txt | tr '\t' ' ' > the_modified_copy.txt
tr ' ' \\t < someFile > someFile
tr ' ' \\t < someFile > someFile
。 - Sam Bisbeels -l | sed "s/ \+/ /g"
。 - Jessawk -v OFS="\t" '$1=$1' file1
命令,我发现如果你有一个以数字0开头的行(例如 0 1 2
),那么这一行将会从结果中被省略。 - Nikola Novak使用Perl:
perl -p -i -e 's/ /\t/g' file.txt
perl -p -i -e 's/\t/ /g' *.java
。 - TimPs/ {4}/
将4个空格缩进转换为制表符。 - CrazyPyrotr [:blank:] \\t
unzip -l some-jars-and-textfiles.zip | tr [:blank:] \\t | cut -f 5 | grep jar
tr [:blank:] \\t
- Ömer An将当前目录下的每个 .js 文件转换为 Tab 的示例命令(只转换前导空格):
find . -name "*.js" -exec bash -c 'unexpand -t 4 --first-only "$0" > /tmp/totabbuff && mv /tmp/totabbuff "$0"' {} \;
下载并运行以下脚本,以递归方式将软制表符转换为硬制表符在纯文本文件中。
将脚本放置在包含纯文本文件的文件夹内并从该文件夹内执行。
#!/bin/bash
find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
echo "Converting... "$file"";
data=$(unexpand --first-only -t 4 "$file");
rm "$file";
echo "$data" > "$file";
}; done;
tr -s '[:blank:]'
tr -s '[:blank:]' '\t'
-c
选项会替换连续的非空格字符。 - wingedsubmariner使用 sed:
T=$(printf "\t")
sed "s/[[:blank:]]\+/$T/g"
或者
sed "s/[[:space:]]\+/$T/g"
astyle
。我发现它非常有用,并且还有几个选项:Tab and Bracket Options:
If no indentation option is set, the default option of 4 spaces will be used. Equivalent to -s4 --indent=spaces=4. If no brackets option is set, the
brackets will not be changed.
--indent=spaces, --indent=spaces=#, -s, -s#
Indent using # spaces per indent. Between 1 to 20. Not specifying # will result in a default of 4 spaces per indent.
--indent=tab, --indent=tab=#, -t, -t#
Indent using tab characters, assuming that each tab is # spaces long. Between 1 and 20. Not specifying # will result in a default assumption of
4 spaces per tab.`
sed 's/[[:blank:]]\+/\t/g' original.out > fixed_file.out
例如,这将减少制表符或空格的数量为一个单一的制表符。
您还可以将多个空格/制表符的情况转换为一个空格:
sed 's/[[:blank:]]\+/ /g' original.out > fixed_file.out
tr
或者sed
。 - Ibrahim