Removing text from a line in a file

Hi All,

I would like to know how to remove text from a line in a file.

eg

[na *oparea* check 0 nul 6376000 nlr 6374000 eul 318000 elr 320000]

to

[na *oparea* check 0]

The 4 sets of numbers are not static ie they change on each line in each different file so if anyone can help that would be great.

Jeremy

awk '{print $1,$2,$3,$4"]"}' inputfilename > outputfilename

try this Perl one liner:

perl -pi -e 's/(\[na\s+\*oparea\*\s+check\s+\d+)\s+nul\s+\d+\s+nlr\s+\d+\s+eul\s+\d+\s+elr\s+\d+\]/\1]/' newfile

Hopefully the entire line does not have to matched and a shorter regexp will suffice:

perl -pi -e 's/^(\Q[na *oparea* check \E\d+).*/$1]/' file

The only advantage is a more readable code. The disadvantage is false matches are possible if the entire line needs to be matched

perl -pi -e 's/^(\Q[na *oparea* check \E\d+).*/$1]/' file

perl -pi -e 's/(\[na\s+\*oparea\*\s+check\s+\d+)\s+nul\s+\d+\s+nlr\s+\d+\s+eul\s+\d+\s+elr\s+\d+\]/\1]/' newfile

I have tried both of these lines, but they just make the output file empty

don't have to use regular expression. Unless i read your requirement wrong,

open(F, "<file") or die "cannot open file:$!\n";
while ( <F> ) {
 if ( /nul/ ) {
  @a = split(/nul/);
  print $a[0] . "]\n";
 } 
}
close(F);

output:

# ./test.pl
[na *oparea* check 0 ]

open(F, "<file") or die "cannot open file:$!\n";
while ( <F> ) {
if ( /nul/ ) {
@a = split(/nul/);
print $a[0] . "]\n";
}
}
close(F);

can you please explain this line by line for me.

open and while loop : perldoc perlopentut
split : perldoc -f split

Same thing can be achieved by

sed 's/\(.*\) nul.*/\1]/' inuput_file

But you are using a regexp (2 of them), just a much simpler one. If that works, is a nice lean solution.

yes, i should've said, "don't have to use too much regular expression". generally, the if the operation is not too complex, simple regex or string functions will suffice.