如何使用 grep 搜索从 1900 年到 2100 年的年份?
例如,如果我有一个 20123320
的变量,我想打印 2012
。
最佳答案
使用 bash 的有趣方式(sh
用户当心!):
如果你想匹配并打印出现在文件 file
中行首的所有这些年份:
printf "^%s\n" {1900..2100} | grep -of - file
如果您有一个包含 20123320
的变量 variable
:
variable=20123320
printf "^%s\n" {1900..2100} | grep -of - <(echo "$variable")
现在请详细说明您想做什么,以便我们给您最合适的答案。
编辑。正如我看到使用其他工具而不是 bash 的其他答案一样和 grep这是 100% bash解决方案:
variable="20123320"
# take the first 4 characters of variable:
year="${variable:0:4}"
# check that year is an integer and that it falls into the given range
if [[ "$year" =~ ^[[:digit:]]+$ ]] && (( 1900<=year && year<=2100)); then
echo "$year"
else
# Do whatever you want here
echo "You dumbo, I couldn't find a valid year in your string"
fi
关于linux - 如何使用 grep 搜索从 1900 年到 2100 年的年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788509/