通过命令转换子字符串

Convert substring through command

基本上,如何进行字符串替换,其中替换的字符串由外部命令转换?

例如,给定行 5aaecdab287c90c50da70455de03fd1e ./2015/01/26/GOPR0083.MP4,如何将行的第二部分 (./2015/01/26/GOPR0083.MP4) 通过管道传输到命令 xargs stat -c %.6Y,然后用结果替换它,以便我们以 5aaecdab287c90c50da70455de03fd1e 1422296624.010000?

结束

这可以通过脚本来完成,但是单行代码会更好。

#!/bin/bash

hashtime()
{
    while read longhex fname; do
        echo "$longhex $(stat -c %.6Y "$fname")"
    done
}

if [ $# -ne 1 ]; then
    echo Usage: ${0##*/} infile 1>&2
    exit 1
fi

hashtime < 

exit 0

# one liner
awk 'BEGIN { args="stat -c %.6Y " } { printf "%s ", ; cmd=args ; system(cmd); }' infile

通常使用 awk sed cut 重新格式化输入。例如:

line="5aaecdab287c90c50da70455de03fd1e ./2015/01/26/GOPR0083.MP4"
echo "$line" |
cut -d' ' -f2- | 
xargs stat -c %.6Y

使用 GNU sed 的单行程序,它将处理整个文件:

sed -E "s/([[:xdigit:]]+) +(.*)/stat -c ' %.6Y' ''/e" file

或者,使用普通 bash

while read -r hash pathname; do stat -c "$hash %.6Y" "$pathname"; done < file