I think I have a really simple question but i can't figure out the answer.
I have this code
[[ "${file_name}" = ${regex} ]] && continue
POSIX version does not support this [[ ]] pattern... Basically what this line does is. If name of the file matches the Extended regular expression, it skips my loop. Is there a way in POSIX norm to do this same thing on one line? or is there any other way to have a word and compare it with E regular expression?
Thank you for your answers.
Use grep -E:
if grep -qE "$regex" "$file_name"; then
If you want to match the content of the variable file_name, pipe it to grep:
if printf "%s\n" "$file_name" | grep -qE "$regex"; then
Related
I'm looking to change a variable with format 8.0.3.0 to 8.0-3.0 in a bash script
So it's always the middle decimal point to a dash
What's the most efficient way to do this?
You can use parameter expansion, like this:
v="8.0.3.0"
echo "${v%*.*.*}-${v#*.*.}"
With GNU sed you can suffix a replacement with the occurence of the match you want to replace :
$ echo "a.b.c.d" | sed 's/\./-/2'
a.b-c.d
If you have a lot of data to handle, it may be worth trying this solution which is not as concise but avoids calling an external program, using internal matching, so may be faster.
string=8.0.3.0
if
[[ $string =~ ^([0-9])[.]([0-9])[.]([0-9])[.]([0-9])$ ]]
then
newstring="${BASH_REMATCH[1]}.${BASH_REMATCH[2]}-${BASH_REMATCH[3]}.${BASH_REMATCH[4]}"
else
echo "ERROR: no match on $string"
fi
If awk is a choice
awk '$0 = gensub( /\./, "-", 2 )' file
8.0-3.0
I am trying to validate user input against a regular expression.
vari=A
if [ $vari =~ [A-Z] ] ;
then
echo "hurray"
fi
The output I am getting is swf.sh[3]: =~: unknown test operator.
Can you please let me know the test operator I can use?
It's not built into Bourne shell, you need to use grep:
if echo "$vari" | grep -q '[A-Z]'; then
echo hurray
fi
If you want to match the whole string, remember to use the regex anchors, ^ and $. Note that the -q flag makes grep quiet, so its only output is the return value, for match/not match.
POSIX shell doesn't have a regular expression operator (or rather, the POSIX test command does not). Instead, you use the expr command to do a (limited) form of regular expression matching.
if expr "$vari" : '[A-Z]' > /dev/null; then
(I say "limited" because it always matches at the beginning of the string, as if the regular expression started with ^.) The exit status is 0 if a match is made; it also writes the number of characters matched to standard output, hence the redirect to /dev/null.
If you are actually using bash, you need to use the [[ command:
if [[ $vari =~ [A-Z] ]]; then
I'm trying to write a bash script that counts all elements in an array that don't begin with the character '-' (it's part of a shell-completion script that counts the arguments and not the options in the words array).
A Python equivalent to what I'm trying to write would be:
len([word for word in words if not word.startswith("-")])
I wrote some code that works fine but since I'm very new to bash scripting, I'm sure that some improvements can be made, and I'm wondering if I missed some better way to implement this that doesn't involve so many lines of code, maybe something that looks more like the Python implementation?
This is what I have:
words=('a' 'b' '-c' 'd' '--foo' 'e')
argcount=0
for word in ${words[#]}
do
if [[ $word =~ ^[^-].*$ ]] ; then
((argcount++))
fi
done
echo $argcount
Any improvement is welcome.
I'd use
for word in "${words[#]}"
which should work even if some argument contain whitespace. Also, instead of a regular expression, you can use a normal pattern matching:
if [[ $word != -* ]] ; then
Other than that, I do not see anything. Bash is not as concise as Python or Perl.
You can also use grep to count the lines for you:
$ words=('a' 'b' '-c' 'd' '--foo' 'e')
$ argcount=$( printf "%s\n" "${words[#]}" | grep -vc "^-" )
(Assuming no word in words can contain an embedded newline, which seems like a safe enough assumption.)
If you must use pure bash, and don't want to use patterns as choroba suggests, you can negate the result of the regular expression match:
if ! [[ $word =~ ^- ]]; then
(( argcount++ ))
fi
I have to write a small bash script that determines if a string is valid for the bash variable naming rules. My script accepts the variable name as an argument. I am trying to pass that argument to the grep command with my regex but everything I tried, grep tries to open the value passed as a file.
I tried placing it after the command as such
grep "$regex" "$1"
and also tried passing it as redirected input, both with and without quotes
grep "$regex" <"$1"
and both times grep tries to open it as a file. Is there a way to pass a variable to the grep command?
Both your examples interpret "$1" as a filename. To use a string, you can use
echo "$1" | grep "$regex"
or a bash specific "here string"
grep "$regex" <<< "$1"
You can also do it faster without grep with
[[ $1 =~ $regex ]] # regex syntax may not be the same as grep's
or if you're just checking for a substring,
[[ $1 == *someword* ]]
You can use the bash builtin feature =~ . Like this:
if [[ "$string" =~ $regex ]] ; then
echo "match"
else
echo "dont match"
fi
I know it is possible to invert grep output with the -v flag. Is there a way to only output the non-matching part of the matched line? I ask because I would like to use the return code of grep (which sed won't have). Here's sort of what I've got:
tags=$(grep "^$PAT" >/dev/null 2>&1)
[ "$?" -eq 0 ] && echo $tags
You could use sed:
$ sed -n "/$PAT/s/$PAT//p" $file
The only problem is that it'll return an exit code of 0 as long as the pattern is good, even if the pattern can't be found.
Explanation
The -n parameter tells sed not to print out any lines. Sed's default is to print out all lines of the file. Let's look at each part of the sed program in between the slashes. Assume the program is /1/2/3/4/5:
/$PAT/: This says to look for all lines that matches pattern $PAT to run your substitution command. Otherwise, sed would operate on all lines, even if there is no substitution.
/s/: This says you will be doing a substitution
/$PAT/: This is the pattern you will be substituting. It's $PAT. So, you're searching for lines that contain $PAT and then you're going to substitute the pattern for something.
//: This is what you're substituting for $PAT. It is null. Therefore, you're deleting $PAT from the line.
/p: This final p says to print out the line.
Thus:
You tell sed not to print out the lines of the file as it processes them.
You're searching for all lines that contain $PAT.
On these lines, you're using the s command (substitution) to remove the pattern.
You're printing out the line once the pattern is removed from the line.
How about using a combination of grep, sed and $PIPESTATUS to get the correct exit-status?
$ echo Humans are not proud of their ancestors, and rarely invite
them round to dinner | grep dinner | sed -n "/dinner/s/dinner//p"
Humans are not proud of their ancestors, and rarely invite them round to
$ echo $PIPESTATUS[1]
0[1]
The members of the $PIPESTATUS array hold the exit status of each respective command executed in a pipe. $PIPESTATUS[0] holds the exit status of the first command in the pipe, $PIPESTATUS[1] the exit status of the second command, and so on.
Your $tags will never have a value because you send it to /dev/null. Besides from that little problem, there is no input to grep.
echo hello |grep "^he" -q ;
ret=$? ;
if [ $ret -eq 0 ];
then
echo there is he in hello;
fi
a successful return code is 0.
...here is 1 take at your 'problem':
pat="most of ";
data="The apples are ripe. I will use most of them for jam.";
echo $data |grep "$pat" -q;
ret=$?;
[ $ret -eq 0 ] && echo $data |sed "s/$pat//"
The apples are ripe. I will use them for jam.
... exact same thing?:
echo The apples are ripe. I will use most of them for jam. | sed ' s/most\ of\ //'
It seems to me you have confused the basic concepts. What are you trying to do anyway?
I am going to answer the title of the question directly instead of considering the detail of the question itself:
"grep a pattern and output non-matching part of line"
The title to this question is important to me because the pattern I am searching for contains characters that sed will assign special meaning to. I want to use grep because I can use -F or --fixed-strings to cause grep to interpret the pattern literally. Unfortunately, sed has no literal option, but both grep and bash have the ability to interpret patterns without considering any special characters.
Note: In my opinion, trying to backslash or escape special characters in a pattern appears complex in code and is unreliable because it is difficult to test. Using tools which are designed to search for literal text leaves me with a comfortable 'that will work' feeling without considering POSIX.
I used both grep and bash to produce the result because bash is slow and my use of fast grep creates a small output from a large input. This code searches for the literal twice, once during grep to quickly extract matching lines and once during =~ to remove the match itself from each line.
while IFS= read -r || [[ -n "$RESULT" ]]; do
if [[ "$REPLY" =~ (.*)("$LITERAL_PATTERN")(.*) ]]; then
printf '%s\n' "${BASH_REMATCH[1]}${BASH_REMATCH[3]}"
else
printf "NOT-REFOUND" # should never happen
exit 1
fi
done < <(grep -F "$LITERAL_PATTERN" < "$INPUT_FILE")
Explanation:
IFS= Reassigning the input field separator is a special prefix for a read statement. Assigning IFS to the empty string causes read to accept each line with all spaces and tabs literally until end of line (assuming IFS is default space-tab-newline).
-r Tells read to accept backslashes in the input stream literally instead of considering them as the start of an escape sequence.
$REPLY Is created by read to store characters from the input stream. The newline at the end of each line will NOT be in $REPLY.
|| [[ -n "$REPLY" ]] The logical or causes the while loop to accept input which is not newline terminated. This does not need to exist because grep always provides a trailing newline for every match. But, I habitually use this in my read loops because without it, characters between the last newline and the end of file will be ignored because that causes read to fail even though content is successfully read.
=~ (.*)("$LITERAL_PATTERN")(.*) ]] Is a standard bash regex test, but anything in quotes in taken as a literal. If I wanted =~ to consider the regex characters in contained in $PATTERN, then I would need to eliminate the double quotes.
"${BASH_REMATCH[#]}" Is created by [[ =~ ]] where [0] is the entire match and [N] is the contents of the match in the Nth set of parentheses.
Note: I do not like to reassign stdin to a while loop because it is easy to error and difficult to see what is happening later. I usually create a function for this type of operation which acts typically and expects file_name parameters or reassignment of stdin during the call.