Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 将日期替换为UNIX Timestam,同时保留行的其余部分_Linux_Bash_Unix_Awk - Fatal编程技术网

Linux 将日期替换为UNIX Timestam,同时保留行的其余部分

Linux 将日期替换为UNIX Timestam,同时保留行的其余部分,linux,bash,unix,awk,Linux,Bash,Unix,Awk,我有这样一句台词 从某处复制到2016年4月13日星期三10:18:25 CEST文件大小 我想将日期转换为Unix时间戳。而该行的其余部分保持不变。我想对完整的文件执行此操作。我能想象的唯一方法是提取日期并转换它,创建一个新文件并填写时间戳。我不确定“文件大小”是否以文件中的一行结尾。你确实用它结束了这一行,但你还写了“…”,这让我想知道是否还有更多的内容。当你问一个涉及文本处理的问题时,这些细节是至关重要的 假设“filesize”以一行结尾,下面的代码可能会有所帮助,否则它将只是一个有用的

我有这样一句台词

从某处复制到2016年4月13日星期三10:18:25 CEST文件大小


我想将日期转换为Unix时间戳。而该行的其余部分保持不变。我想对完整的文件执行此操作。我能想象的唯一方法是提取日期并转换它,创建一个新文件并填写时间戳。

我不确定“文件大小”是否以文件中的一行结尾。你确实用它结束了这一行,但你还写了“…”,这让我想知道是否还有更多的内容。当你问一个涉及文本处理的问题时,这些细节是至关重要的

假设“filesize”以一行结尾,下面的代码可能会有所帮助,否则它将只是一个有用的模式,供您根据需要进行修改

while read -r line; do
    # The part containing the date and the file size.
    details_str="${line#*at }"
    # The date part.
    date_str="${details_str% *}"
    # The file size.
    file_size="${details_str#$date_str }"

    # Arrange date part, so it can be acceptable by 'date'
    # [Correct] 10:18:25 Wed 13 Apr CEST 2016
    # [Incorrect] Wed 13 Apr 10:18:25 CEST 2016
    read -r d n m t z y <<< "$date_str"
    printf -v date_str '%s %s %s %s %s %s' "$t" "$d" "$n" "$m" "$z" "$y"

    # Convert date part to milliseconds since epoch.
    millis=$(date --date="$date_str" '+%s')

    # Print formatted line.
    printf '%s %s %s\n' "${line% $details_str}" "$millis" "$file_size"

done < /path/to/your/file
测试(脚本名称为sof):


好主意!向我们展示您尝试过的命令行,否则有些人会认为您希望我们编写代码……filesize结束了吗?您好,谢谢这一行,您的假设是正确的,filesize结束了这一行。我甚至不知道bash可以为我展示这个文本操作thx。
copy to somewhere1 from somewhere at Wed 13 Apr 10:18:25 CEST 2016 20K
copy to somewhere2 from somewhere at Wed 13 Apr 09:14:25 CEST 2016 30K
copy to somewhere3 from somewhere at Wed 13 Apr 12:18:25 CEST 2016 40K
./sof 
copy to somewhere1 from somewhere at 1460535505 20K
copy to somewhere2 from somewhere at 1460531665 30K
copy to somewhere3 from somewhere at 1460542705 40K