Home > Software engineering >  How can I get only the first line in a file that starts with "1." followed by any characte
How can I get only the first line in a file that starts with "1." followed by any characte

Time:12-02

I have this file

1.1some text
2.some text
1.line I need

How can I print only the first line in a file that start with "1." followed by any character except a number? I expect this:

1.line I need

my code is this

q=$(grep "^[0-9].[a-z]"  "file")
echo $q

Thank you

CodePudding user response:

With your shown samples, please try following grep code. Simple explanation would be: Using grep's m1 option to print only first match and exit from program then in main program mentioning regex to match lines that start from 1. followed by a non-digit character, if match is found then print the line.

grep -m1 '^1\.[^0-9]'  Input_file

CodePudding user response:

How can I print only the first line in a file that start with 1.followed by any character except a number?

Using sed, you can use:

sed '/^1\.[^0-9]/!d;q' file

1.line I need

Details:

  • -n: Suppresses regular output
  • /^1\.[^0-9]/: Search for a line starting with 1 followed by a dot and a non-digit
  • !d: Deletes all non-matching lines
  • q: Quits further processing

Similar solution in awk would be:

awk '/^1\.[^0-9]/{print; exit}' file
  • Related