I would like to know how can I grep out (exclude) variables inside a file?
For example file.txt:
PATH1=/path/to/file
PATH2=/path/to/anotherfile
PATH3=/path/to/thirdfile
TEST=$(echo $RANDOM)
* * * * *\5 top -n 1 > /tmp/$TEST
* * * * * echo hello # = for deletion
I want to print only the cron job without variables: eg:
* * * * *\5 top -n 1 > /tmp/$TEST
* * * * * echo hello # = for deletion
note that there are equal signs at the end, i need to keep these lines as well. tailing this file is not a solution, there can be more than just 1 line that is not a variable of course. any ideas?
With Vixie cron, a crontab line is:
a comment if the first non-blank character is #
an environment setting if the first non-blank character is a letter or _
a cron command if the first non-blank character is a digit, * or @
a blank line if there is no non-blank character
otherwise, an error.
So to grep for case 3 (cron command):
grep -E '^[[:blank:]]*[0-9*@]'
Alternatively, to remove case 2 (environment setting) but leave everything else, including comments and errors:
grep -Ev '^[[:blank:]]*[a-zA-Z_]'
Use grep -v
grep -v '=' filename
Or you can grep
only for the required entry.
$ grep '\*' filename
* * * * *\5 top -n 1 > /tmp/$TEST
使用以下grep,它将仅排除变量设置行:
grep -iv '^[[:blank:]]*[_a-z][_a-z0-9]*[[:blank:]]*='
I have an answer! You question made me think why do you want to filter declaration out...because declarations does not " do actual work " . In this sense they are invisible :)
So my solution filters out invisible commands like declaration...of course if this example.txt contains rm -Rf /
that would be funny or other unix commands still makes no output so you can combine it with some kind of =
char search.
So my point is that declaration makes no output, other words would do...here is my funny answer:
$ export IFS=$'\n'; for line in $(cat /tmp/example.txt);do if [ "$(eval $line 2>&1 )" != "" ];then echo "RESULT PRINTING: $line";else echo "DEF NOT PRINTING: $line";fi; done
DEF NOT PRINTING: PATH1=/path/to/file
DEF NOT PRINTING: PATH2=/path/to/anotherfile
DEF NOT PRINTING: PATH3=/path/to/thirdfile
DEF NOT PRINTING: TEST=$(echo $RANDOM)
RESULT PRINTING: * * * * *\5 top -n 1 > /tmp/$TEST
RESULT PRINTING: * * * * * echo hello # = for deletion
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.