If shell script file
I try to write a shell script but I have some difficulties to do a special if statement. I would like that if it find a value in a file it do something.
My file is like this:
1, 2, 2, 8
0, 0, 3, 3 5, 0, 4, 5 1, 4, 5, 3 1, 0, 8, 7I do this to extract some information
sed -i '/^[0-9][0-9]*, [0-9][0-9]*, 3,/d' file.txt
But I would like to put this in a if condition, like if the third number is a 3 or 4 or 5 I do the sed else I do something else I try this:
if [ '/*, *, [3,5],/d' ]; then
echo 'ok'
else
echo'fail'
fi
But it doesn't wo开发者_开发问答rk, it always prints ok.
Do you know how I can do this?
please provide clearer examples next time
#!/bin/bash
# tested with bash 4
while read -r x x Y x
do
case "$Y" in
"3," ) echo "ok";;
*) echo "Not ok";;
esac
done < file
' *'
will match an undetermined number of spaces.
You should put [0-9]*
instead.
You can use Internal-Field-Separator and let the shell take care about parsing:
#!/bin/sh
# let's create the input file
echo '5, 2, 3, 5' > /tmp/myfile
# function will output third argument
third() { IFS=', '; echo $3; }
# now let's print the third value from the input file
third $(cat /tmp/myfile)
See man sh, and look for the IFS to learn more about it.
If you are not forced to use shell-only solution you can get the third field by awk:
#!/bin/sh
THIRD=$(awk -F', ' '{print $3}' < /tmp/myfile)
精彩评论