1

I have file called "quota.txt" as below:

DISK_info_start:/usr
Disk: /usr
CURRENT=81
DISK_info_end:/usr

DISK_info_start:/usr/var
Disk: /usr/tmp
CURRENT=1
DISK_info_end:/usr/var

I have a variable as below:

entry=/usr

I want extract paragraph starting From DISK_info_start:$entry to DISK_info_end:$entry like this:

DISK_info_start:/usr
Disk: /usr
CURRENT=81
DISK_info_end:/usr

I tried this command:

sed -n "\|DISK_info_start:$entry$|,\|DISK_info_end:$lines$|p" quota.txt

but, it is not doing an exact match which is what i was looking for.

Can you tweak this command for me or provide an alternative?

3 Answers3

2

Using awk:

Use awk in paragraph mode:

awk -v RS= '/DISK_info_start\:\/usr\n/' quota.txt

If you match multiple paragraphs, add -v ORS="\n\n", otherwise awk removes blank lines between the matches.

Note that you need \n instead of $ to find the end of the line as the latter marks the end of the paragraph only.

If you need variables, make sure to quote the /:

entry=/usr
awk -v RS= "/DISK_info_start\:${entry//\//\\\/}\n/" quota.txt

Using perl:

perl has a paragraph mode, too (-00):

perl -00 -ne '/DISK_info_start\:\/usr\n/ && print' quota.txt

Add | tr -s '\n' to avoid printing the empty line at the end.


Using sed:

You could also use sed like this:

sed -n '/DISK_info_start:\/usr$/,/DISK_info_end:\/usr$/p' quota.txt

This will not really find paragraphs but from match to match.

pLumo
  • 22,565
1

Try awk, it is good for text processing:

awk 'index($0, "DISK_info_start:"D"\n")==1' RS="" ORS="\n\n" D="/usr" quota.txt

DISK_info_start:/usr
Disk: /usr
CURRENT=81
DISK_info_end:/usr
  • +1 as it not only looks for match inside a paragraph but (at least as far as I understand it) that the match is in the first line of the paragraph. – pLumo Oct 10 '18 at 11:59
  • Ah Ok! I misunderstand what you meant! –  Oct 10 '18 at 12:28
-1

You can try: grep -A3 DISK_info_start:$entry quota.txt

mrc02_kr
  • 2,003