1

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
 .
 .
1
  • Post some relevant input data and your expected output. Mar 10, 2014 at 15:04

5 Answers 5

2

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.

0
2

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.

1
  • \s* would work as well, thought I'd make it really obvious that it handles lines starting with WS. Mar 10, 2014 at 15:29
2

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
8
  • pay attention - before number 0 or 1 I have the char "*" could be other char
    – user1121951
    Mar 10, 2014 at 14:55
  • @Eytan what do you mean? The only condition that is checked is the line starting with 2.
    – fedorqui
    Mar 10, 2014 at 14:57
  • its mean that - number 0 in the begining of the line could be after some other char
    – user1121951
    Mar 10, 2014 at 14:59
  • @Eytan I still don't know what you mean. Do you want to print from the first line having 0? What's the importance of 0 in your sample input?
    – fedorqui
    Mar 10, 2014 at 15:01
  • the target is to print until the line that start with number 2 ( not include spaces or TAB ) because before number 2 could be spaces or TABs
    – user1121951
    Mar 10, 2014 at 15:05
1

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.