bash - 提取变量的星期几

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8398913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:08:25  来源:igfitidea点击:

bash - extract day of week of variable

linuxbashshellunixscripting

提问by toop

What is the syntax to extract the day of the week from a stored date variable? The dateinfileformat is always [alphanum]_YYYYMMDD.

从存储的日期变量中提取星期几的语法是什么?该dateinfile格式始终[alphanum]_YYYYMMDD

In this pseudocode example, trying to get dayofweekto store Saturday:

在这个伪代码示例中,尝试dayofweek存储星期六:

#! /bin/bash 

dateinfile="P_20090530"
dayofweek="$dateinfile -u +%A"

回答by Shawn Chin

[me@home]$ date --date=${dateinfile#?_} "+%A"
Saturday

Or, to put it as you've requested:

或者,按照您的要求说:

[me@home]$ dayofweek=$(date --date=${dateinfile#?_} "+%A")
[me@home]$ echo $dayofweek
Saturday

回答by golimar

date -d $(echo $dateinfile | cut -f2 -d_) -u +%A

The inner expression separates the 20090530from P_20090530, and the outer one extracts the day of week from that date

内部表达式将20090530from分开P_20090530,外部表达式从该日期中提取星期几

回答by Jason Bullough

I needed the same output recently and googled upon this, but I had the same problem stating Bad Substition error.

我最近需要相同的输出并对此进行了搜索,但是我遇到了同样的问题,指出 Bad Substition 错误。

I then read the date manual and made my version up as follows:

然后我阅读了日期手册并按如下方式制作了我的版本:

#! /bin/sh
dateinfile="P_20090530"
dayofweek=`date --reference $dateinfile +%A`
echo $dayofweek