[英]sed retrieve part of line
I have lines of code that look like this:我有如下代码行:
hi:12345:234
(second line) hi:12345:234
(第二行)
How do I write a line of code using the sed command that only prints out the 2nd item in the second line?如何使用仅打印出第二行中的第二项的 sed 命令编写一行代码?
My current command looks like this:我当前的命令如下所示:
sed -n '2p' file
which gets the second line, but I don't know what regex to use to match only the 2nd item '12345' and combine with my current command sed -n '2p' file
获取第二行,但我不知道使用什么正则表达式仅匹配第二项 '12345' 并与我当前的命令结合
Could you please try following, written and tested with shown samples in GNU sed
.您能否尝试使用 GNU sed
中显示的示例进行跟踪、编写和测试。
sed -n '2s/\([^:]*\):\([^:]*\).*/\2/p' Input_file
Explanation: Using -n
option of sed
will stop the printing for all the lines and printing will happen only for those lines where we are explicitly mentioning p
option to print(later in code).说明:使用sed
的-n
选项将停止所有行的打印,并且仅对我们明确提到要打印的p
选项的那些行进行打印(稍后在代码中)。 Then mentioning 2s
means perform substitution on 2nd line only.然后提到2s
意味着仅在第 2 行执行替换。 Then using regex and sed
's capability to store matched regex into a temp buffer by which values can be retrieved later by numbering 1,2...and so on
.然后使用正则表达式和sed
的能力将匹配的正则表达式存储到临时缓冲区中,稍后可以通过编号1,2...and so on
来检索值。 Regex is basically catching 1st part which comes before first occurrence of :
and then 2nd part after first occurrence of :
to till 2nd occurrence of :
as per OP's request.正则表达式基本上是捕获第一次出现之前的第一部分:
然后是第一次出现之后的第二部分:
直到第二次出现:
根据 OP 的要求。 So while doing substitution mentioning /2
will replace whole line with 2nd value stored in buffer as per request, then mentioning p
will print that part only in 2nd line.因此,在进行替换时,提及/2
将根据请求将整行替换为存储在缓冲区中的第二个值,然后提及p
将仅在第二行打印该部分。
A couple of solutions:几个解决方案:
echo "hi:12345:234" | sed -n '2s/.*:\([0-9]*\):.*/\1/p'
echo "hi:12345:234" | sed -n '2{s/^[^:]*://; s/:.*//p; q}'
echo "hi:12345:234" | awk -F':' 'FNR==2{print $2}'
All display 12345
.全部显示12345
。
sed -n '2s/.*:\([0-9]*\):.*/\1/p'
only displays the captured value thanks to -n
and p
option/flag. sed -n '2s/.*:\([0-9]*\):.*/\1/p'
由于-n
和p
选项/标志,仅显示捕获的值。 It matches a whole string capturing digits between two colons, \1
only keeps the capture.它匹配两个冒号之间捕获数字的整个字符串, \1
仅保留捕获。
The sed -n '2{s/^[^:]*://;s/:.*//p;q}'
removes all from start till first :
, all from the second to end, and then quits ( q
) so if your file is big, it will be processed quicker. sed -n '2{s/^[^:]*://;s/:.*//p;q}'
删除从开始到第一个:
的所有内容,从第二个到结束的所有内容,然后退出( q
) 所以如果你的文件很大,它会被更快地处理。
awk -F':' 'FNR==2{print $2}'
splits the second line with a colon and fetches the second item. awk -F':' 'FNR==2{print $2}'
用冒号分割第二行并获取第二项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.