iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
✂️
Extracting multiple lines between specific patterns using shell scripts
I do not use sed and regular expressions (since behavior varies depending on the environment).
This is a method to find the line numbers of the start and end lines via string search and then extract them using awk.
Extracting from a file
AAA
BBB
CCC
DDD
EEE
FFF
GGG
#!/usr/bin/env bash
IN_FILE=target.txt
LINE_BGN=$(sed -n '/BBB/=' $IN_FILE)
LINE_END=$(sed -n '/EEE/=' $IN_FILE)
echo $LINE_BGN
echo $LINE_END
cat $IN_FILE |awk "$LINE_BGN<=NR && NR<=$LINE_END{print \$0}"
2
5
BBB
CCC
DDD
EEE
Extracting via pipe
#!/usr/bin/env bash
DATA1="AAA\nBBB\nCCC\nDDD\nEEE\nFFF\nGGG\n"
LINE_BGN=$(echo -e $DATA1 |sed -n '/BBB/=')
LINE_END=$(echo -e $DATA1 |sed -n '/EEE/=')
echo $LINE_BGN
echo $LINE_END
echo -e $DATA1 |awk "$LINE_BGN<=NR && NR<=$LINE_END{print \$0}"
The -e option of echo -e is required when passing a string that includes newline characters.
The output is the same.
Discussion