Copy the section to a new file

I have a text file,

!--- Marker one --!
aaaa
bbbb
cccc
dddd
!--- Marker two --!
eeee
ffff
!--- Marker three --!
gggg
hhhh
iiii


And I need to copy from Marker two (to the end of Marker two) to a new file using Bash.

!--- Marker two --!
eeee
ffff

It becomes a separate file.

+3
source share
2 answers

Awk

$ awk '/Marker two/{f=1;print;next}f&&/Marker/{exit}f' file
!--- Marker two --!
eeee
ffff

bash

#!/bin/bash

flag=0
while read -r line
do
  case "$line" in
     *"Marker two"*)
         flag=1; echo $line;continue
  esac
  case "$flag $line" in
   "1 "*"Marker"* ) exit;;
   "1"* ) echo $line;;
  esac
done <"file"

sed

$ sed  -n '/Marker two/,/Marker three/{/Marker three/!p}' file
!--- Marker two --!
eeee
ffff
+8
source

The classic case of what you can do with 'sed':

sed -n '/^!--- Marker two --!/,/^!--- Marker three --!/{
        /^!--- Marker three --!/d;p;}' \
    infile > outfile

The only result is if the first marker is displayed more than once in the data. The patterns correspond to the beginning of the section and the beginning of the next section; the commands in braces remove the line to start the second section and print all the other lines.

"w" ( ), :

sed -n -e '/!--- Marker one --!/,/!--- Marker two --!/w file1' \
       -e '/!--- Marker three --!/,/!--- Marker four --!/w file2' infile

Etc.

+1

Source: https://habr.com/ru/post/1757764/


All Articles