I've a file with information like this

Info A: 1
Info B: 2
Info C: 3
Info D: 4

Info A: 1
Info B: 2
Info C: 123
Info D: 4

Now I'm trying to get the line with Info C but I need it separately. I need a command to get the output of Info C of the first block and a command to get the Info C from the second block. This command works for me, to get the Info C of both blocks. In the first part of the command, I'm deleting all the stuff except the lines with Info C. In the second part of the command, I'm deleting the string "Info C: "

cat test2 | sed -e '/Info C: /!d' -e 's/Info C: //'

The output contains only the value:


Now, to get it separately, I've tried several arguments for sed but nothing works for me.

The following solution works fine for me. I just print the first or the last line

cat test2 | sed -e '/Info C: /!d' -e 's/Info C: //' | sed -n '$p'
cat test2 | sed -e '/Info C: /!d' -e 's/Info C: //' | sed -n '1p'

But I wonder, if there is a solution without a second pipeline for sed?

  • Are there always two blocks in your input and is it guaranteed that each block contains a line matching Info C ? Keep in mind you can always save the result into an array and use ${array[0]} and ${array[1]} later instead of saving into separate variables... Oct 16 '16 at 18:15

Well, if your shell supports arrays, you can do:

$ infoC=( $(sed -n 's/Info C: \(.*\)/\1/p' file ) )
$ echo ${infoC[0]}
$ echo ${infoC[1]}

Or, with GNU sed:

infoC=($(sed -rn 's/Info C: (.*)/\1/p' file ))

I'm using a simpler sed command here. The -n suppresses normal output, so it only prints the lines you tell it to. The substitution operator matches the lines with Info C: and captures (with the parentheses) the value which is saved as \1. So it will replace the line with \1 and print it (the p at the end).

The var=( $(command) ) is a way of saving the output of command in the array var. The first element is then ${var[0]}, the second ${var[1]} etc. Here, the array name is infoC.

  • 1
    /Info C: /s///p
    – Costas
    Oct 16 '16 at 19:12
  • If you'd like it at full sed -n '/Info C: /s///p' file
    – Costas
    Oct 16 '16 at 19:16
  • @Costas yeah, my bad, I deleted my previous comment. Could you also explain why that works? It looks like its replacing nothing with nothing. It would be great if you could post an answer showing this and explaining how it works. It looks like the substitution operator deletes anything matched by the match operator.
    – terdon
    Oct 16 '16 at 19:17
  • @Costas - you don't need -n + p just sed '/Info C: /!d;s///' Oct 16 '16 at 19:23
  • sed -rn 's/Info C: (.*)/\1/p' can be simplified to sed -n 's/Info C: //p'
    – Sundeep
    Oct 17 '16 at 3:14
cat test2 | sed -e '/Info C: /!d' -e 's/Info C: //' | sed -n '1p;$p'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.