# Shell script to merge the lines between two patterns and print the entire file

**URL:** <https://community.unix.com/t/shell-script-to-merge-the-lines-between-two-patterns-and-print-the-entire-file/392335>\
**Category:** Shell Programming and Scripting\
**Created:** [October 22, 2023, 10:20am UTC](https://community.unix.com/t/shell-script-to-merge-the-lines-between-two-patterns-and-print-the-entire-file/392335 "2023-10-22T10:20:38Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![MadeInGermany](https://community.unix.com/letter_avatar/madeingermany/32/6_449c533f586939b6e5f246632a46421f.png) [@MadeInGermany](https://community.unix.com/u/MadeInGermany)\
**Post date:** [October 22, 2023, 4:09pm UTC](https://community.unix.com/t/shell-script-to-merge-the-lines-between-two-patterns-and-print-the-entire-file/392335/2 "2023-10-22T16:09:35Z")

</div>

> [@kshitij](#):
>
> awk '/Module State/{a=1;next}/6.4/{a=0}1' FILE.csv

I think you want to use the `a` as a state variable, and act according to its state.  
First, it must be `6\.4` in a regular expression, because an unescaped dot means "any character".  
The action is missing.  
If it's to append the current line, then it could be

```plaintext
awk 'a{buf=(buf FS $0)} /Module State/{a=1; buf=$0} /6\.4/{a=0; print buf}' FILE.csv

```

I use a buf variable:

- if `a == 1` then add the current line to `buf` with a leading space (append)
- if `Module State` is met then set `a` to `1` and store the line in `buf`
- if `6.4` is met then set `a` to `0` and print `buf`

In this case it's doable without buffering:

```plaintext
awk 'a{printf " %s", $0} /Module State/{a=1; printf "%s", $0} /6\.4/{a=0; printf "\n"}' FILE.csv

```

- if `a == 1` then print the current line with a leading space and no ending newline (append)
- if `Module State` is met then set `a` to `1` and print the current line without a newline
- if `6.4` is met then set `a` to `0` and print an ending newline

I see opening and closing quotes, so maybe you just need my tip

> [@Tip: Remove newlines in quoted fields in a csv](https://community.unix.com/t/tip-remove-newlines-in-quoted-fields-in-a-csv/390809):
>
> A couple of times I had to remove newlines in quoted fields in a csv. (Once because the Excel import failed in certain locales. Was a bug of course.) I did not find a robust script solution on the Internet. So I created the following script with embedded sed code: #!/bin/sh # Remove newlines in quoted fields in a csv input sed ' # Save input in hold buffer h :Q1 # Substitute an opening " s/"// # If success jump to :Q2 tQ2 # Restore input; jump to the end (next cycle) x; b :Q2 # S…

---

_[View the full topic](https://community.unix.com/t/shell-script-to-merge-the-lines-between-two-patterns-and-print-the-entire-file/392335)._
