如何使'cut'命令将同一个sequental分隔符视为一个?

mba*_*off 303 unix bash cut delimiter

我正在尝试从基于列的"空格"调整的文本流中提取某个(第四个)字段.我正在尝试以cut下列方式使用该命令:

cat text.txt | cut -d " " -f 4

不幸的是,cut不会将多个空格视为一个分隔符.我本可以通过awk进行管道传输

awk '{ printf $4; }'

或者sed

sed -E "s/[[:space:]]+/ /g"

崩溃的空间,但我想知道是否有任何办法处理cut和本地几个分隔符?

kev*_*kev 537

尝试:

tr -s ' ' <text.txt | cut -d ' ' -f4
Run Code Online (Sandbox Code Playgroud)

tr手册页:

-s, --squeeze-repeats   replace each input sequence of a repeated character
                        that is listed in SET1 with a single occurrence
                        of that character

  • 这里不需要"猫".你可以将`<text.txt`直接传递给`tr`.http://en.wikipedia.org/wiki/Cat_%28Unix%29#Useless_use_of_cat (23认同)

fed*_*qui 90

当你在你的问题中发表评论时,awk真的是要走的路.要使用cut可以连同tr -s挤压的空间,如千电子伏的答案节目.

但是,让我为未来的读者介绍所有可能的组合.解释在测试部分.

tr | 切

tr -s ' ' < file | cut -d' ' -f4
Run Code Online (Sandbox Code Playgroud)

AWK

awk '{print $4}' file
Run Code Online (Sandbox Code Playgroud)

庆典

while read -r _ _ _ myfield _
do
   echo "forth field: $myfield"
done < file
Run Code Online (Sandbox Code Playgroud)

SED

sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' file
Run Code Online (Sandbox Code Playgroud)

测试

给定此文件,让我们测试命令:

$ cat a
this   is    line     1 more text
this      is line    2     more text
this    is line 3     more text
this is   line 4            more    text
Run Code Online (Sandbox Code Playgroud)

tr | 切

$ cut -d' ' -f4 a
is
                        # it does not show what we want!


$ tr -s ' ' < a | cut -d' ' -f4
1
2                       # this makes it!
3
4
$
Run Code Online (Sandbox Code Playgroud)

AWK

$ awk '{print $4}' a
1
2
3
4
Run Code Online (Sandbox Code Playgroud)

庆典

这会按顺序读取字段.通过使用_我们指出这是一个一次性变量作为忽略这些字段的"垃圾变量".这样,我们将$myfield文件存储为文件中的第4个字段,无论它们之间是否有空格.

$ while read -r _ _ _ a _; do echo "4th field: $a"; done < a
4th field: 1
4th field: 2
4th field: 3
4th field: 4
Run Code Online (Sandbox Code Playgroud)

SED

这会捕获三组空格而没有空格([^ ]*[ ]*){3}.然后,它抓住任何东西,直到作为第四个领域的空间,它最终打印出来\1.

$ sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' a
1
2
3
4
Run Code Online (Sandbox Code Playgroud)

  • `awk`不仅优雅而简单,还包含在VMware ESXi中,缺少`tr`. (2认同)
  • @ user121391使用`awk`的另一个原因! (2认同)

ari*_*elf 25

最短/最友好的解决方案

在对太多限制感到沮丧之后cut,我写了自己的替代品,我称之为cuts"切断类固醇".

cut提供了最简单的解决方案,以及许多其他相关的剪切/粘贴问题.

解决这一特定问题的一个例子是:

$ cat text.txt
0   1        2 3
0 1          2   3 4

$ cuts 2 text.txt
2
2
Run Code Online (Sandbox Code Playgroud)

cuts 支持:

  • 自动检测文件中最常见的字段分隔符(+覆盖默认值的能力)
  • multi-char,mixed-char和regex匹配分隔符
  • 从具有混合分隔符的多个文件中提取列
  • 除了行首之外,从行尾(使用负数)的偏移量
  • 自动并排粘贴列(无需paste单独调用)
  • 支持现场重新排序
  • 用户可以更改个人偏好的配置文件
  • 非常注重用户友好性和极简主义所需的打字

以及更多.这些都不是标准提供的cut.

另见:https://stackoverflow.com/a/24543231/1296044

来源和文件(免费软件):http://arielf.github.io/cuts/