help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Rewriting file from bash


From: Greg Wooledge
Subject: Re: Rewriting file from bash
Date: Sun, 3 Oct 2021 12:53:19 -0400

On Sun, Oct 03, 2021 at 06:36:40PM +0300, Tapani Tarvainen wrote:
> On Sun, Oct 03, 2021 at 05:16:04PM +0200, Julius Hamilton 
> (juliushamilton100@gmail.com) wrote:
> > How could I print the nth region of text of a file that is between blank
> > newline regions, at the command line? So for example:
> > 
> > file.txt:
> > 
> > line1
> > 
> > line2
> > line3
> > 
> > line4
> > 
> > 
> > 
> > $ region[2]
> > 
> > would return
> > 
> > line2
> > line3
> > 
> > I presume this would be with grep, sed and/or awk.
> 
> Yes, not really a bash thing. Easiest with awk:
> 
> awk -v RS= 'NR==2' file.txt

Just for the record, here's one way to do it in bash:

region=() i=1
while IFS= read -r line; do
  if [[ $line = "" ]]; then
    ((i++))
  else
    region[i]+="$line"$'\n'
  fi
done

This leaves an "extra" trailing newline on each array element, which
you may need to deal with later.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]