Scripting sed脚本打印每行的前三个单词
我想知道如何使用sed执行以下操作: 我只需要保留每行的前三个单词。 例如,以下文本:Scripting sed脚本打印每行的前三个单词,scripting,sed,Scripting,Sed,我想知道如何使用sed执行以下操作: 我只需要保留每行的前三个单词。 例如,以下文本: the quick brown fox jumps over the lazy bear the blue lion is hungry 将转变为: the quick brown the blue lion 在awk中,你可以说: {print $1, $2, $3} 在这种情况下,我建议awk: awk '{print $1,$2,$3}' ./infile 如果需要sed脚本,可以尝试: ech
the quick brown fox jumps over the lazy bear
the blue lion is hungry
将转变为:
the quick brown
the blue lion
在awk中,你可以说:
{print $1, $2, $3}
在这种情况下,我建议
awk
:
awk '{print $1,$2,$3}' ./infile
如果需要sed脚本,可以尝试:
echo "the quick brown fox jumps over the lazy bear" | sed 's/^\([a-zA-Z]\+\ [a-zA-Z]\+\ [a-zA-Z]\+\).*/\1/'
但我认为使用cut更容易:
echo "the quick brown fox jumps over the lazy bear" | cut -d' ' -f1,2,3
这是一个带有
sed
的丑陋的:
$ echo the quick brown fox jumps over the lazy bear | sed 's|^\(\([^[:space:]]\+[[:space:]]\+\)\{2\}[^[:space:]]\+\).*|\1|'
the quick brown
只是使用外壳
while read -r a b c d
do
echo $a $b $c
done < file
我把“-E”放在那里是为了与OSX兼容。其他Unix系统可能需要,也可能不需要
编辑:该死的-脑屁。使用以下命令:
% sed -E 's/(([^ ]+ ){3}).*/\1/' <<END
the quick brown fox jumps over the lazy bear
the blue lion is hungry
END
the quick brown
the blue lion
%sed-E的/([^]+){3}.*/\1/'您可以像这样使用cut
:
cut -d' ' -f1-3
如果Perl是一个选项:
perl-lane“打印”$F[0]$F[1]$F[2]”文件
或
perl-lane'print join”“@F[0..2]”文件
Cut不能处理所用空格的变化。在sed
命令中也不能包含一个文本空格(顺便说一句,它不需要转义)。注意:当我添加这个问题时,我忘记了“Cut”,这是执行此任务的正确工具:Cut-F-3-d+1使用sed
,可获得更简洁的解决方案-尽管您可能希望编辑您的帖子以删除第一次尝试。谢谢。事实上,我应该意识到这是“削减”的任务,而不是“sed”。剪切-f-3输入文件。注意-f-3
相当于-f1-3
。也就是说,-3
的意思是:所有字段都是3
。我不知道,谢谢。我怀疑我会继续写-f1-3
,不过为了清楚起见,因为我会忘记缩写'puts$F[0..2]。join”“
对于ruby来说更简洁一些。Brilliant Thank正在寻找从运行ec2实例的命令中去掉第一个单词的东西,正在使用sed和cut,但是awk非常适合我的要求感谢这一点,但有点不清楚,所以我会添加awk-vORS=''{print$1}'
(其中我使用-vORS='
,因为我希望单词空格分开。高尔夫:awk'{NF=3}1'
% sed -E 's/(([^ ]+ ){3}).*/\1/' <<END
the quick brown fox jumps over the lazy bear
the blue lion is hungry
END
the quick brown
the blue lion
cut -d' ' -f1-3