Poisson
Poisson

Reputation: 1623

Extracting a string from a sentence

I have a file that looks like this

the vote will take place tomorrow at card (0.046786214525982)
vote will take place tomorrow at card noon (0.027725129127836) 
vote will take place tomorrow at card am (0.024548598987843)

And I want to extract only this part of each line

the vote will take place tomorrow at card
vote will take place tomorrow at card noon
vote will take place tomorrow at card am

My Perl script is this

 perl -ne 'print [split /(/]->[0]' 8-8TRI.txt

But it does not work

It says

Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE / at -e line 1.

Upvotes: 0

Views: 114

Answers (3)

Borodin
Borodin

Reputation: 126722

Your regular expression in split /(/ is invalid because ( is a special metacharacter inside a regex and needs a corresponding closing ) to go with it.

You could escape your opening parenthesis with a backslash \( but the shell will also eat backslashes if you use a one-line command, so it is clearer to use a character class [(].

Like this

perl -l -pe "s/[(].+//" myfile

This uses a substitution s/// to remove the first open parenthesis and everything after it in each line.

Note that it won't remove any spaces or tabs before the open parenthesis, so the output will contain invisible trailing space characters

the vote will take place tomorrow at card 
vote will take place tomorrow at card noon 
vote will take place tomorrow at card am 

Upvotes: 1

mpapec
mpapec

Reputation: 50647

perl -ne 'print [ split /\(/ ]->[0]' 8-8TRI.txt
                         ^__ backslash for '('

You don't need array reference, so

perl -ne 'print( (split /\(/ )[0] )' 8-8TRI.txt

Upvotes: 2

anubhava
anubhava

Reputation: 785156

You can use perl like this:

perl -pe 's/^([^(]*).*$/\1/' file
the vote will take place tomorrow at card 
vote will take place tomorrow at card noon 
vote will take place tomorrow at card am 

Upvotes: 0

Related Questions