如何用固定字符串替换部分路径?

时间:2017-12-24 17:16:01

标签: string shell replace path

我想从一行中的路径字符串稍微改变目录名称 例如,如果给定的字符串是
    './dir1/dir2/dir3/xxx.txt'

我想得到     './dir1/fix_string_as_suffix'

我想将它与下面的find命令结合起来,虽然它还没有修复。

find . -type d \( -name 'vendor' \) -prune -o -type f -name '*.txt' -print | cut -d'/' -f1,2

5 个答案:

答案 0 :(得分:1)

您可以使用sed

s='./dir1/dir2/dir3/xxx.txt'
sed -E 's~^(([^/]*/){2}).*~\1~' <<< "$s"

./dir1/

答案 1 :(得分:1)

使用IFS&amp; printf 内置

根据您是否要使用标准实用程序(如 cut sed awk),在shell中执行所需操作的方法不止一种,或者如果你想限制自己在shell本身内发现的扩展和内置。一种方法是将路径拆分为组件,然后使用 printf 命令或内置命令重新加入它们。例如:

path='./dir1/dir2/dir3/xxx.txt'

IFS='/' read -ra dirs <<< "$path"
printf '%s' "${dirs[0]}/" "${dirs[1]}/" "..." $'\n'

如果要将其转换为单行,请使用分号加入命令和/或使用curly braces for command grouping。但是,可读性胜过简洁,特别是在shell编程中。

答案 2 :(得分:0)

使用[class.base.init]/9命令:

;

使用prefix=`echo $path | cut -d/ -f1,2` ; echo "$prefix/$suffix" 连接上面的行以将其放在一行:

{{1}}

答案 3 :(得分:0)

我认为这就是你要找的东西

find . -type d \( -name 'vendor' \) -prune -o -type f -name '*.txt' -exec sh -c 'echo "${1%/*}/fix_string_as_suffix"' fstrasuff {} \;

答案 4 :(得分:0)

实际上,我的结果如下。

find . -type d \( -name 'vendor' \) -prune -o -type f -name '*.txt' -print | cut -d'/' -f1,2 | uniq | awk '{print $1"/..."}'