les lignes de filtrage par motif de script bash
Question
J'ai deux variables, un texte et une autre avec des motifs. Et je veux filtrer les lignes, les modèles correspondants. Comment puis-je faire?
Mon script ressemble à ceci
# get ignore files list
IGNORE=`cat ignore.txt`
# get changed files list
CHANGED=`git diff --name-only $LAST_COMMIT HEAD`
# remove files, that should be ignored from change list
for IG in $IGNORE; do
echo $CHANGED
$CHANGED=`cat $CHANGED | grep -v $IG`
done
La solution
Vous pouvez fournir le fichier de configuration directement à grep
# get changed files list and remove files that should be ignored
CHANGED=$(git diff --name-only $LAST_COMMIT HEAD | grep -vf ignore.txt)
echo $CHANGED
(je recommande d'utiliser $()
au lieu de contre-apostrophes.)
Par ailleurs, cette ligne:
$CHANGED=`cat $CHANGED | grep -v $IG`
devrait probablement ressembler à ceci:
CHANGED=`echo $CHANGED | grep -v $IG`
Si vous deviez le garder.
Autres conseils
# Disable globbing
set -f
# Collect variables
IGNORE=$(cat ignore.txt)
CHANGED=$(...)
# Apply each pattern in turn
for pattern in $IGNORE
do
# Reset the current list of candidates
CANDIDATES=
for candidate in $CHANGED
do
# Apply the pattern
CANDIDATES="$CANDIDATES ${candidate%$pattern}"
done
# Update the CHANGED list
CHANGED=$CANDIDATES
done
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow