如何在shell中剪切字符串的第一列(变长)

36
如何在shell中剪切字符串的第一列(变长)?
字符串示例:
23006 help.txt
我需要输出23006。
3个回答

60

许多方式:

cut -d' ' -f1 <filename # If field separator is space
cut -f1 <filename  # If field separator is tab
cut -d' ' -f1 <filename | cut -f1  # If field separator is space OR tab
awk '{print $1}' filename
while read x _ ; do echo $x ; done < filename

不知何故,当我使用“cut”选项将“ps”输出导入时,显示结果中唯一的条目是第一列(由OP指定)长度为5的条目,长度为3或4的条目则不是。在显示的输出之前有一个空白区域,我猜这个空间在行数(术语高度)上与上述行相等,并且隐藏了3/4个字符宽的第一列条目。使用“awk”的方法效果很好。 - 0xc0de
ps 命令会给出格式化的输出(就像 printf %5d 一样)。因此,当 cut 使用空格作为分隔符时,它会将前导空格(对于较小的 PID 数字)视为分隔符。因此,它会打印第一个空格之前的所有内容(在这种情况下为空)。 - anishsane

12
cut -d " " -f1 test.txt

其中test.txt包含您的输入行


6

这个对我有效

cut -d' ' -f2-

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接