0

how to print text between two specific words using awk, sed ?

$ ofed_info | awk '/MLNX_OFED_LINUX/{print}'
MLNX_OFED_LINUX-4.1-1.0.2.0 (OFED-4.1-1.0.2):
$

Output required:-

4.1-1.0.2.0
asokan
  • 199
  • 1
  • 11
  • 1
    asokan, always do add your efforts in your post too in code tags. – RavinderSingh13 May 29 '18 at 10:51
  • 1
    I did added the effort on code tag which is using awk ! – asokan May 29 '18 at 10:53
  • [How to use sed/grep to extract text between two words?](https://stackoverflow.com/q/13242469/), [sed or awk to print lines between words](https://stackoverflow.com/a/3551731), [Extract text between two strings repeatedly using sed or awk?](https://stackoverflow.com/q/13386080/), [Sed to extract text between two strings](https://stackoverflow.com/q/16643288/), [Extract data between two strings using either AWK or SED](https://stackoverflow.com/q/16814473), [How to select lines between two marker patterns which may occur multiple times with awk/sed](https://stackoverflow.com/q/17988756), etc – jww May 29 '18 at 11:26

3 Answers3

0

Following awk may help you here.(considering that your input to awk will be same as shown sample only)

your_command | awk '{sub(/[^-]*/,"");sub(/ .*/,"");sub(/-/,"");print}' 

Solution 2nd: With sed solution now.

your_command | sed 's/\([^-]*\)-\([^ ]*\).*/\2/'

Solution 3rd: Using awk's match utility:

your_command | awk 'match($0,/[0-9]+\.[0-9]+\-[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/){print substr($0,RSTART,RLENGTH)}'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • didn't work, got this output "4.11.0.2.0 " – asokan May 29 '18 at 10:40
  • @asokan, check now and let me know? – RavinderSingh13 May 29 '18 at 10:42
  • 2
    Not my downvote, but I'll repeat my advice to abstain from answering obvious duplicates. E.g. the [Stack Overflow `bash` tag wiki](/tags/bash/info) has a good selection of canonical answers to very common questions. – tripleee May 29 '18 at 11:39
  • 1
    @RavinderSingh13: See https://stackoverflow.com/questions/50559897/replace-line-with-space-and-backslash-with-a-string-containing-spaces/50559951#comment88151230_50559897 – Inian May 29 '18 at 12:37
0

You may use this sed:

echo 'MLNX_OFED_LINUX-4.1-1.0.2.0 (OFED-4.1-1.0.2):' |
sed -E 's/^[^-]*-| .*//g'

4.1-1.0.2.0

This sed command removes text till first hyphen from start or text starting with space towards end.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Try this:

ofed_info | sed -n 's/^MLNX_OFED_LINUX-\([^ ]\+\).*/\1/p'

The sed command only selects lines starting with the keyword and prints the version attached to it.

oliv
  • 12,690
  • 25
  • 45