10

I have a file with the following contents:

(((jfojfojeojfow 
//
hellow_rld
(((jfojfojeojfow
//
hellow_rld

How can I extract every line that starts with a parenthesis?

  • 3
    For some reason, I read "Grep beginning of time"... – Mateen Ulhaq Jun 22 '15 at 7:20
26

The symbol for the beginning of a line is ^. So, to print all lines whose first character is a (, you would want to match ^(:

  1. grep

    grep '^(' file
    
  2. sed

    sed -n '/^(/p' file
    
6

Using perl

perl -ne '/^\(/ && print' foo

Output:

(((jfojfojeojfow 
(((jfojfojeojfow

Explanation (regex part)

  • /^\(/

    • ^ assert position at start of the string
    • \( matches the character ( literally
4

Here is a bash one liner:

while IFS= read -r line; do [[ $line =~ ^\( ]] && echo "$line"; done <file.txt

Here we are reading each line of input and if the line starts with (, the line is printed. The main test is done by [[ $i =~ ^\( ]].

Using python:

#!/usr/bin/env python2
with open('file.txt') as f:
    for line in f:
        if line.startswith('('):
            print line.rstrip()

Here line.startswith('(') checks if the line starts with (, if so then the line is printed.

3

awk

awk '/^\(/' testfile.txt

Result

$ awk '/^\(/' testfile.txt                   
(((jfojfojeojfow 
(((jfojfojeojfow

Python

As python one-liner:

$ python -c 'import sys;print "\n".join([x.strip() for x in sys.stdin.readlines() if x.startswith("(")])' < input.txt    
(((jfojfojeojfow
(((jfojfojeojfow

Or alternatively:

$ python -c 'import sys,re;[sys.stdout.write(x) for x in open(sys.argv[1]) if re.search("^\(",x)]' input.txt

BSD look

look is one of the classic but little known Unix utilities, which appeared way back in AT&T Unix version 7. From man look:

The look utility displays any lines in file which contain string as a prefix

The result:

$ look "(" input.txt
(((jfojfojeojfow 
(((jfojfojeojfow
2

You may do the inverse.

grep -v '^[^(]' file

or

sed '/^[^(]/d' file
  • If the input file contains empty lines, the blank lines are also displayed. – A.B. Jun 22 '15 at 15:31
1

Use the grep command for this. Assuming the file with the mentioned content is called t.txt:

user:~$ grep '^(' t.txt
(((jfojfojeojfow
(((jfojfojeojfow

With '--color' as further argument you can even see in color in the terminal what matches. This instruction also do not match empty lines.

  • 4
    That will print all lines containing a (, not only those that start with one. – terdon Jun 21 '15 at 13:07
  • As terdon said. – kos Jun 21 '15 at 13:54
  • 1
    Yes. Missed the '^' character to start the match at the beginning of the line. Sorry for that. – thedler Jun 22 '15 at 15:49
  • 1
    Now it's better =) +1 – A.B. Jun 22 '15 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.