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 20:43:38 +0300

On Sun, Oct 03, 2021 at 12:53:19PM -0400, Greg Wooledge (greg@wooledge.org) 
wrote:

> > 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

Just for fun, here's an alternative (not a better one - for practical
purposes the loop solution is definitely better):

a=$(< file.txt)
mapfile -d $'\f' -t region <<<${a//$'\n\n'/$'\n\f'}
echo "${region[1]}"

As mapfile cannot use multi-character delimiters, that replaces second
of two consecutive newlines with a single formfeed first and uses it
as the delimiter for mapfile. So this will fail if there're formfeeds
in the file (could use some other character, unfortunately NUL doesn't
seem to work there).

Replacing the region is easy, too:

region[1]="replacement"$'\n'

Printing the entire array can be done, e.g., like this;

printf "%s\n" "${region[@]}"

It does print an extra newline at the end though.

-- 
Tapani Tarvainen



reply via email to

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