linux - 如何使用 grep 搜索从 1900 年到 2100 年的年份?

标签 linux bash sed grep

如何使用 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")

现在请详细说明您想做什么,以便我们给您最合适的答案。

编辑。正如我看到使用其他工具而不是 的其他答案一样和 这是 100% 解决方案:

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/

相关文章:

python - 使用python将波斯字符串保存到mysql数据库中

linux - "getent group A"从哪里获取A组的信息?

bash 脚本 : started with $! 而不是#!并得到了神秘的行为。发生了什么?

linux - 在bash中使用lftp设置umask

使用 `clone()` 创建子进程。为什么 `wait()` 不等待它终止?

Linux: 'ls' 所有jpg文件在csv中递归

linux - 变量赋值退出shell脚本

regex - sed one-liner 删除所有单个换行符?

linux - sed:捕获组的输出值到文件中

bash - 使用 bash 脚本操作文件