【发布时间】:2018-11-28 13:22:45
【问题描述】:
我正在尝试获取文件路径中的最后 4 个目录以及文件名。我在具有 MinGW64 的 Windows 机器上执行此操作。显然这没有“rev”命令,所以我必须自己做:
#!/bin/bash
input="$1"
reverse=""
len=${#input}
for (( i=$len-1; i>=0; i-- ))
do
reverse="$reverse${input:$i:1}"
done
printf "$reverse"
如果我做一个简单的~/reverse.sh 'hello world' 输出:dlrow olleh
但是,如果我这样做:
echo $(~/reverse.sh "/c/Users/myusername/5thfolder/4thfolder/3rdfolder/2ndfolder/1stfolder/this_is_my_target_file.sql") | cut -d"/" -f5-
我的输出是这样的:
redlofht4/redlofht5/emanresuym/sresU/c/
我希望它能够反转输入文件名,然后将该输出 (lqs.elif_tegrat_ym_si_siht/redlofts1/redlofdn2/redlofdr3/redlofht4/redlofht5/emanresuym/sresU/c/) 传递给 cut。然后 cut 将采用前 5 个字段,我将得到输出 lqs.elif_tegrat_ym_si_siht/redlofts1/redlofdn2/redlofdr3/redlofht4/
然后我可以再次反转以获得我需要的输出。
【问题讨论】:
-
为什么将命令放在子shell中?
$(...)。您的脚本打印到标准输出,因此您不需要回显。删除 echo 和 subshell,输出应该通过管道传送到您的cut命令。 -
您的代码似乎做对了。由于您在反向字符串中选择第 5 个字段,因此您不会获得完整的文件名。
-
我的系统有一个
rev命令可以反转输入的每一行。但它来自一个“util-linux”包,所以 YMMV。 -
供您参考,
rev可能在这里有用:echo "123" | rev输出321 -
致所有说要使用“rev”的人——这显然是我应该做的。我就是不能——它不在我的系统上(它使用 MinGW64(如我所说))。它就在前几行中。
标签: linux bash git-bash cut mingw-w64