help-bash
[Top][All Lists]
Advanced

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

Re: Rewriting file from bash


From: Tapani Tarvainen
Subject: Re: Rewriting file from bash
Date: Sun, 3 Oct 2021 18:36:40 +0300

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

> How could I then write a replacement for that region, from the command line
> (i.e. not using Vim or something)? Something like:
> 
> $ region [2] “this is the replacement line”

E.g.,

repl="this is the replacement line"
awk -v RS= -v ORS='\n\n' -v r="$repl" 'NR==2{$0=r}{print}' file.txt

-- 
Tapani Tarvainen



reply via email to

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