-2

I will try to explain better. I also checked the comments but still dont have luck with the replace.

grep part is returning true, because the regexp seems to be ok. But sed, doesnt replace

This is the script:

#!/bin/bash
# All of these:
# FILE1: &VAR1 = 1111
# FILE1: &VAR1     =     '1111'
# FILE1: &VAR1  =  1111;
# With:
# &VAR2 = 'NEW';
#
# SEARCH STRING
LAREXP="&VAR1\s*=\s*'?[1]{4}'?"
# REPLACE STRING
LACADE="&VAR2 = 'NEW'";
# ALL FILES WITH NAME STARTING WITH ZZ
for f in /home/u028619/zz*; do
# SEARCH IF THE SEARCH STRING EXISTS, THIS IS ALWAYS TRUE, OK
    if grep -qE "$LAREXP" "$f"; then
# REPLACE THE STRING, THIS IS WHATS DOESN'T WORK
        sed -i "s/$LAREXP/$LACADE/g" "$f"
    fi
done
#
exit 0
Ruben
  • 114
  • 12
  • 2
    Possible duplicate of [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – Aaron Jun 28 '18 at 08:47
  • 1
    You don't need much more than to learn how to use the quantifiers `?` and `*` to solve this problem. They're nicely explained in the accepted answer of the question I've linked as duplicate. – Aaron Jun 28 '18 at 08:50

2 Answers2

1

This regex will make sure that the semicolon and white-space are optional, and the quotation marks match (if it starts with single/double, it will match the corresponding one at the end):

/&VAR1\s*=\s*(['"])?1{4}\1;?/
C.Holloway
  • 11
  • 4
0

Thanks @Aaron! I've read a little and I think I got it:

/&VAR1\s*\=\s*\'VALUE\'\;/

@Tripleee thanks. That worked with Javascript in an online tester, I changed to Unix and tried, but it doesnt work. I changed VALUE to search por 1111. Any help?

grep "\&VAR1\s*\=\s*'[1]{4}'\;"

EDIT: Its done, [] and {} are extender regexp so this works:

grep -E "\&VAR1\s*\=\s*'[1]{4}'\;"
Ruben
  • 114
  • 12