[All variants] remove first pair of parentheses

How to remove first pair of parentheses and content in them from the beginning of the line?

Here's the list:

(ok)-test
(ok)-test-(ing)
(some)-test-(ing)-test
test-(ing)

Desired result:

test
test-(ing)
test-(ing)-test
test-(ing)

Here's what I already tried with GNU sed:

sed -e 's/^(.*)//'
sed -r 's/^\(.*\)//'

Solution preferences order: sh/bash, grep, sed, awk, perl, other

How about:

sed 's/^[(][^)]*[)]-//'
1 Like

maybe this will work too?

awk '/^\(/ {sub(/\(/,"");sub(/\)/,"")}1'  infile
1 Like

Yes, it does remove parentheses, but not the content in them.
Next time I should ask precisely.

How about:

$ cat usertail 
TMP=~/tmp.$$
REM="ok some"
echo "(ok)-test
(ok)-test-(ing)
(some)-test-(ing)-test
test-(ing)" > $TMP

for rem in $REM
do 	sed s,\($rem\),,g  -i $TMP
done
sed s,^\-,,g $TMP

$ ./usertail
test
test-(ing)
test-(ing)-test
test-(ing)

Hope this helps

1 Like

Perhaps, but your output file specification was precise. I think Chubler_XL got it right, no?

Another way of writing it would be:

sed 's/^([^)]*)-//' file

Note that the thing different from your original attempt is that the . is replaced by [^)] (to force lazy matching, rather than the standard greedy matching) and the - is specified, so it will be removed too.

1 Like

Hi.

Using bash operator "=~" with extended regular expressions:

#!/usr/bin/env bash

# @(#) s2	Demonstrate extended regular expressions, bash =~.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C

FILE=${1-data1}

pl " Input data file $FILE:"
cat $FILE

pl " Expected results:"
cat expected-output.txt

pl " Results:"
PATTERN='(^[(][^)]*[)]-)(.*)'
while read line
do
  db ' Working on line ['"$line"']'
  if [[ $line =~ $PATTERN ]]
  then
    printf "%s\n" "${BASH_REMATCH[2]}"
  else
    printf "%s\n" $line
  fi
done <$FILE

exit 0

producing:

$ ./s2

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian 5.0.8 (lenny, workstation) 
bash GNU bash 3.2.39

-----
 Input data file data1:
(ok)-test
(ok)-test-(ing)
(some)-test-(ing)-test
test-(ing)

-----
 Expected results:
test
test-(ing)
test-(ing)-test
test-(ing)

-----
 Results:
test
test-(ing)
test-(ing)-test
test-(ing)

Best wishes ... cheers, drl

1 Like