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
fed*_*qui 90
当你在你的问题中发表评论时,awk真的是要走的路.要使用cut可以连同tr -s挤压的空间,如千电子伏的答案节目.
但是,让我为未来的读者介绍所有可能的组合.解释在测试部分.
tr -s ' ' < file | cut -d' ' -f4
Run Code Online (Sandbox Code Playgroud)
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 -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)
$ 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 '{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)
这会捕获三组空格而没有空格([^ ]*[ ]*){3}.然后,它抓住任何东西,直到作为第四个领域的空间,它最终打印出来\1.
$ sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' a
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
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 支持:
paste单独调用)以及更多.这些都不是标准提供的cut.
另见:https://stackoverflow.com/a/24543231/1296044
来源和文件(免费软件):http://arielf.github.io/cuts/