gpt4 book ai didi

Bash:从包含完整路径的读取行中提取用户路径 (/home/userID) 并替换为 "~"

转载 作者:行者123 更新时间:2023-11-29 09:27:47 25 4
gpt4 key购买 nike

我一次构建一个 bash 脚本文件。我像我一样学习去。但是此时我无法在网上找到任何可以帮助我的东西:我需要从大字符串中提取子字符串,我发现使用 ${}(花括号)的两种方法都行不通。

第一个,${x#y},没有做它应该做的事情。

第二个,${x:p}${x:p:n},不断报告错误替换。
它似乎只适用于常量。

${#x} 返回字符串长度作为文本,而不是数字,这意味着它不适用于 ${x:p}${x:p:n}.

事实是,让 bash 做很多数学运算似乎真的很难。除了 for 语句。但这只是在计算。这不是 for 循环的任务。

我在这里合并了我的脚本文件,以帮助大家理解我在做什么。它用于处理 PureBasic 源文件,但您只需更改 grep 的“--include=”参数,它就可以搜索其他类型的文本文件。

#!/bin/bash
home=$(echo ~) # Copy the user's path to a variable named home
len=${#home} # Showing how to find the length. Problem is, this is treated
# as a string, not a number. Can't find a way to make over into
# into a number.
echo $home "has length of" $len "characters."
read -p "Find what: " what # Intended to search PureBasic (*.pb?) source files for text matches
grep -rHn $what $home --include="*.pb*" --exclude-dir=".cache" --exclude-dir=".gvfs" > 1.tmp
while read line # this checks for and reads the next line
do # the closing 'done' has the file to be read appended with "<"
a0=$line # this is each line as read
a1=$(echo "$a0" | awk -F: '{print $1}') # this gets the full path before the first ':'
echo $a0 # Shows full line
echo $a1 # Shows just full path
q1=${line#a1}
echo $q1 # FAILED! No reported problem, but failed to extract $a1 from $line.
q1=${a0#a1}
echo $q1 # FAILED! No reported problem, but failed to extract $a1 from $a0.
break # Can't do a 'read -n 1', as it just reads 1 char from the next line.
# Can't do a pause, because it doesn't exist. So just run from the
# terminal so that after break we can see what's on the screen .
len=${#a1} # Can get the length of $a1, but only as a string
# q1=${line:len} # Right command, wrong variable
# q1=${line:$len} # Right command, right variable, but wrong variable type
# q1=${line:14} # Constants work, but all $home's aren't 14 characters long
done < 1.tmp

最佳答案

以下作品:

x="/home/user/rest/of/path"
y="~${x#/home/user}"
echo $y

会输出

~/rest/of/path

如果你想在变量中使用“/home/user”,比如说前缀,你需要在#之后使用$,即${x#$prefix},我认为是你的问题。

关于Bash:从包含完整路径的读取行中提取用户路径 (/home/userID) 并替换为 "~",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32525057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com