[英]printing selected portions of selected rows using awk
Assume I have a file called 'file.csv' that contains the following data 假设我有一个名为“ file.csv”的文件,其中包含以下数据
A:qwe
B:ert
C:rty
How would I be able to print out everything before the ':' in rows 2 and 3. So I want my output to be just B and C. Have tried 我如何能够打印出第2行和第3行中':'之前的所有内容,所以我希望输出仅是B和C。
cat file.csv | awk -F ':' '{print $1}'
but that prints out A as well and not too sure how to implement 'NR==2,NR==3' to this 但这也会打印出A,但不太确定如何对此执行'NR == 2,NR == 3'
Awk seems like ridiculous overkill here. Awk在这里似乎太荒谬了。 How about this: 这个怎么样:
tail -n 2 | cut -d ":" -f 1
For a range of lines from n to m, you can use sed|cut
combination 对于从n到m的行范围,可以使用sed|cut
组合
sed -n '2,3p' file | cut -d: -f1
or just awk
或只是awk
awk -F: 'NR>=2 && NR<=3 {print $1}' file
sed
is easier than awk
for this sed
比awk
更容易
sed -n '2,3s/:.*//p' file.csv
But I'm wondering if you really meant that you want the second and third lines, as opposed to some other criteria. 但是我想知道您是否真的想要第二行和第三行,而不是其他标准。
Perl solution: Perl解决方案:
perl -F: -lane 'print $F[0] if $. > 1' file
Prints first field of input if $. 如果$,则打印输入的第一个字段。 (line number variable) > 1 (行号变量)> 1
These command-line options are used: 使用以下命令行选项:
n
loop around every line of the input file, do not automatically print every line n
循环输入文件的每一行,不要自动打印每一行
l
removes newlines before processing, and adds them back in afterwards l
在处理之前先删除换行符,然后再添加回去
a
autosplit mode – perl will automatically split input lines into the @F array. a
自动分割模式- perl的将自动分割输入线到@F阵列。 Defaults to splitting on whitespace 默认为在空白处分割
F
autosplit modifier, in this example splits on ':' F
autosplit修饰符,在此示例中以':'分隔
e
execute the perl code e
执行perl代码
Given: 鉴于:
$ echo "$tgt"
A:qwe
B:ert
C:rty
You can use Perl and the 'flip-flop' operator to print the file or text between two line numbers: 您可以使用Perl和“触发器”运算符在两个行号之间打印文件或文本:
$ echo "$tgt" | perl -lne 'print $1 if /(^[^:]+)/ and 2..3'
B
C
Which works for a file also (obviously) 哪个也适用于文件(显然)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.