Reputation: 71
How would I change my Regex to stop after the first match of the word?
My text is:
-rwxr--r-- 1 bob123 bob123 0 Nov 10 22:48 /path/for/bob123/dir/to/file.txt
There is a variable called owner
, the first arg from cmd:
owner=$1
My regex is: ^.*${owner}
My match ends up being:
-rwxr--r-- 1 bob123 bob123 0 Nov 10 22:48 /path/for/bob123
But I only want it to be: -rwxr--r-- 1 bob123
.
Upvotes: 1
Views: 323
Reputation: 627410
You do not need a regex here, use string manipulation and concatenation:
text='-rwxr--r-- 1 bob123 bob123 0 Nov 10 22:48 /path/for/bob123/dir/to/file.txt'
owner='bob123'
echo "${text%%$owner*}$owner"
# => -rwxr--r-- 1 bob123
See the online Bash demo.
The ${text%%$owner*}
removes as much text as possible from the end of string (due to %%
) up to and including the $owner
, and - since the $owner
text is removed - "...$owner"
adds $owner
back.
Upvotes: 0
Reputation: 4539
By adding a question mark: ^.*?${owner}
. This will make the *
quantifier non-greedy. But use -P
option: grep -P
to use Perl-compatible regular expression.
https://regex101.com/r/ThGpcq/1.
Upvotes: 0