Conditional search and delete using SED / Shell script

Hi,
I want to perform a conditional search and remove my search string.

Input string: "abcdaabcadgfaarstab"
Character to search: "a"
Condition: Remove all "a" in the input string except if it is "aa"
Output string: "bcdaabcdgfaarstb"

Can you please help me in this?

echo "abcdaabcadgfaarstaba" | perl -e '$x=<>; $x=~s/([^a])a([^a])/$1$2/g; $x=~s/^a([^a])|([^a])a$/$1$2/g; print "$x"'
1 Like

But is there a solution without using perl. Something using sed, awk as we do not have perl in target.

Try...

echo "abcdaabcadgfaarstab" | sed 's/\(^\|[^a]\)a\([^a]\|$\)/\1\2/g'
1 Like

@Ygor: I too tried that initially. But it wouldn't work if there was an 'a' at the end, as in "abcdaabcadgfaarstaba". Surprising, but it isn't considering "a" in the end even though the regex has a $.. So, I wrote one to check and substitute separately.

@dominiclajs: Try this:

echo "abcdaabcadgfaarstaba" | sed "s:\([^a]\)a\([^a]\):\1\2:g" | sed "s:^a\([^a]\)\|\([^a]\)a$:\1\2:g"

Little tricky .. :wink:

$ echo "abcdaabcadgfaarstab" | sed 's,aa,?,g;s,a,,g;s,?,aa,g'