linux - Bash cut 不使用 stdin

标签 linux bash git-bash cut mingw-w64

我正在尝试获取文件路径中的最后 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") |剪切-d"/"-f5- 我的输出是这样的: redlofht4/redlofht5/emanresuym/sresU/c/

我希望它反转输入文件名,然后传递输出 (lqs.elif_tegrat_ym_si_siht/redlofts1/redlofdn2/redlofdr3/redlofht4/redlofht5/emanresuym/sresU/c/ ) 进行剪切。然后 cut 将采用前 5 个字段,我将得到输出 lqs.elif_tegrat_ym_si_siht/redlofts1/redlofdn2/redlofdr3/redlofht4/ 然后我可以再次反转以获得我需要的输出。

最佳答案

你需要在

中使用-f-5而不是-f5-
... | cut -d"/" -f-5

您还可以使用 sed 获取文件路径中的最后 4 个目录以及文件名:

echo "/fff/eee/ddd/ccc/bbb/aaa/file.sql" | sed -r 's|.*(/.*/.*/.*/.*/.*)$|\1|'

会输出

/ddd/ccc/bbb/aaa/file.sql

关于linux - Bash cut 不使用 stdin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50930776/

相关文章:

git - 启动 GitBash 时未执行 .bashrc

python - 使用pip download命令时如何设置平台

linux - 了解 GDB 和段错误消息

bash - 如何使用 Bash 插入 SQLite 数据库?

python - "Fatal: too many params"从 python 调用 bash 命令时,直接在 git bash 中使用相同命令没有错误

windows - Git,切换分支时出现错误 : "Deletion of directory ' <dirname >' failed. Should I try again?" Started after I set custom folder icon

c - 在 c 中正确使用 ftw()

linux - 如何在 SED 或 AWK 中使用 if, else?

bash - 将时间戳添加到 tee 的输出,但不是原始输出

Bash 脚本,数组未按预期创建