Question

I have the file with the following format

How to cut the file until the line that start with number 2 ( not include line 2 )

before the new line with number 2 could be spaces or TABs ,

remark - implementation can be done with ksh or awk or sed or perl one liner etc

file:

* 0    

 Any text
 Any text
 .
 .

 1

 Any text
 Any text
 .
 .

 2

 Any text
 Any text
 .
 .

 3

 Any text
 Any text
 .
 .
Was it helpful?

Solution 4

Perl one-liner:

perl -pwe 'exit if $_ =~ /^\s*2/' file

This allows for any number of spaces between the start of the line and the number 2

OTHER TIPS

Just exit when you encounter the line you want to stop at:

awk '/[[:space:]]*2/{exit}1' file

Update: [[:space:]] will take care of spaces, tabs etc.

Use sed to delete everything after (and including) the matching line

$ sed '/^[      ]*2/,$d' input.txt

That's a space and a tab in the character class.

You can "play" with a flag, that deactivates when the line is found:

awk 'BEGIN{f=1} /^2/{f=0} f' file

BEGIN{f=1} initializes the flag as true. /^2/{f=0} unsets it when a line starts with 2, f, when true, prints the line.

To also check lines having 2 after some spaces, you can do:

awk 'BEGIN{f=1} /\s*2/{f=0} f' file

Use the instruction Q with sed so that it doesn't parse the rest of the file once it has found the appropriate end line:

sed '/^\s*2/Q' file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top