这一行一直工作到第二个字段中出现空白。

svn status | grep '\!' | gawk '{print $2;}' > removedProjs

有没有办法让awk打印所有2美元或更大的东西?(3、4美元. .直到我们不再有专栏了?)

我想我应该补充一点,我正在使用Cygwin在Windows环境中执行此操作。


当前回答

我想把建议的答案扩展到字段可能由几个空格分隔的情况——我想这就是OP不使用cut的原因。

我知道OP问了关于awk的问题,但sed方法在这里可以工作(例如从第5列打印到最后一列):

pure sed approach sed -r 's/^\s*(\S+\s+){4}//' somefile Explanation: s/// is the standard command to perform substitution ^\s* matches any consecutive whitespace at the beginning of the line \S+\s+ means a column of data (non-whitespace chars followed by whitespace chars) (){4} means the pattern is repeated 4 times. sed and cut sed -r 's/^\s+//; s/\s+/\t/g' somefile | cut -f5- by just replacing consecutive whitespaces by a single tab; tr and cut: tr can also be used to squeeze consecutive characters with the -s option. tr -s [:blank:] <somefile | cut -d' ' -f5-

其他回答

更新:

如果你想在保留空格和制表符的同时不使用任何函数调用,那么:

echo  "    1   2  33  4444 555555 \t6666666    " | 

{m,g}awk ++NF FS='^[ \t]*[^ \t]*[ \t]+|[ \t]+$' OFS= 

=

2  33  4444 555555     6666666

===================

你可以让它更直接:

 svn status | [m/g]awk   '/!/*sub("^[^ \t]*[ \t]+",_)'

 svn status |   [n]awk '(/!/)*sub("^[^ \t]*[ \t]+",_)'

自动处理管道中早期的grep,以及在删除$1后删除额外的FS,额外的好处是保留原始输入的其余部分,而不是用空格覆盖制表符(除非这是想要的效果)

如果你非常确定$1不包含需要regex转义的特殊字符,那么就更容易了:

mawk         '/!/*sub($!_"[ \t]+",_)'
gawk -c/P/e '/!/*sub($!_"""[ \t]+",_)' 

或者如果你更喜欢自定义FS+OFS来处理这一切:

mawk 'NF*=/!/' FS='^[^ \t]*[ \t]+' OFS='' # this version uses OFS

我对这里提供的awk解决方案都不满意,因为我想提取前几列,然后打印其余的,所以我转而使用perl。下面的代码提取了前两列,并按原样显示其余部分:

echo -e "a  b  c  d\te\t\tf g" | \
  perl -ne 'my @f = split /\s+/, $_, 3; printf "first: %s second: %s rest: %s", @f;'

与Chris Koknat的perl解决方案相比,优点是实际上只从输入字符串中分离出前n个元素;字符串的其余部分根本没有被分割,因此保持完整。我的示例混合使用空格和制表符来演示这一点。

要更改应该提取的列的数量,请将示例中的3替换为n+1。

Perl:

@m=`ls -ltr dir | grep ^d | awk '{print \$6,\$7,\$8,\$9}'`;
foreach $i (@m)
{
        print "$i\n";

}

有一个重复的问题,使用cut的答案更简单:

 svn status |  grep '\!' | cut -d\  -f2-

-d指定delimeter(空格),-f指定列列表(所有列都从第2个开始)

awk '{ for(i=3; i<=NF; ++i) printf $i""FS; print "" }'

Lauhub在这里提出了这个正确、简单、快速的解决方案