Search code examples
bashunixgrepunix-head

head output till a specific line


I have a bunch of files in the following format.

A.txt:

some text1      
more text2    
XXX
more text  
....  
XXX
.  
.  
XXX 
still more text  
text again  

Each file has at least 3 lines that start with XXX. Now, for each file A.txt I want to write all the lines till the 3rd occurrence of XXX (in the above example it is till the line before still more text) to file A_modified.txt.

I want to do this in bash and came up with grep -n -m 3 -w "^XXX$" * | cut -d: -f2 to get the corresponding line number in each file.

Is is possible to use head along with these line numbers to generate the required output?

PS: I know a simple python script would do the job but I am trying to do in this bash for no specific reason.


Solution

  • A simpler method would be to use awk. Assuming there's nothing but files of interest in your present working directory, try:

    for i in *; do awk '/^XXX$/ { c++ } c<=3' "$i" > "$i.modified"; done
    

    Or if your files are very big:

    for i in *; do awk '/^XXX$/ { c++ } c>=3 { exit }1' "$i" > "$i.modified"; done