如何调用包含文件路径而不是文件路径末尾的文件的变量的字符串内容? Bash/Linux
How do I call the string content of a variable containing a filepath instead of the file at the end of the filepath? Bash/Linux
我想给脚本一个文件路径,取文件名,将文件名赋给一个变量,然后对文件路径下的文件执行一个动作。
不幸的是,我不知道如何访问变量的字符串内容,而不是文件路径中保存的文件。
TestingScript.sh:
#!/bin/bash
egrep -o "[^/]+$" #get name of the file from the end of the filepath
wc -l #count the number of lines in the file
Testing.txt
This
/is
the
text
运行它:
./TestingScript.sh "/User/Me/Directory/Testing.txt"
而不是返回:
Testing.txt
4 /User/Me/Directory/Testing.txt
这是输出:
/is
4 /User/Me/Directory/Testing.txt
正在将评论转化为答案。
运行 echo "" | grep -E -o '^/.+
' 会 运行 grep -E
(又名 egrep
)在名称上,但正则表达式与的最后一个组件不匹配名称(为此您需要 '[^/]+$'
,并且名称不能以 /
结尾)。但是你想要的命令是 basename
(尤其是因为 basename /x/y/z/
报告 z
甚至修改后的 grep
正则表达式也失败了)。顺便说一句,grep
(egrep
) 的 -o
选项是一个 GNU 扩展。
Why does this matter "The -o
option to grep
(egrep
) is a GNU extension"?
并非我使用的机器上所有 grep
的副本都是 GNU grep
— 全世界都不是 Linux 盒子。如果非 Linux 框上的 grep
版本根本不支持 -o
选项或不使用该选项,您将收到一条错误消息或不同的行为与 GNU grep
的含义相同。如果您只处理 Linux 个框,则不必担心;这就是为什么这是一个偶然的评论。
I did not have an issue with '[^/]+$'
— why do you say it fails?
因为echo /x/y/z/ | grep -o -E '[^/]+$'
没有输出。如果没有尾部斜杠(用于强制名称为目录),则没有问题。这是一个极端主义的案例——你的剧本怎么会被极端的输入破坏。如果 /x/y/z/
是一个目录(或不存在),wc
命令也会失败。
我想给脚本一个文件路径,取文件名,将文件名赋给一个变量,然后对文件路径下的文件执行一个动作。
不幸的是,我不知道如何访问变量的字符串内容,而不是文件路径中保存的文件。
TestingScript.sh:
#!/bin/bash
egrep -o "[^/]+$" #get name of the file from the end of the filepath
wc -l #count the number of lines in the file
Testing.txt
This
/is
the
text
运行它:
./TestingScript.sh "/User/Me/Directory/Testing.txt"
而不是返回:
Testing.txt
4 /User/Me/Directory/Testing.txt
这是输出:
/is
4 /User/Me/Directory/Testing.txt
正在将评论转化为答案。
运行 echo "" | grep -E -o '^/.+
' 会 运行 grep -E
(又名 egrep
)在名称上,但正则表达式与的最后一个组件不匹配名称(为此您需要 '[^/]+$'
,并且名称不能以 /
结尾)。但是你想要的命令是 basename
(尤其是因为 basename /x/y/z/
报告 z
甚至修改后的 grep
正则表达式也失败了)。顺便说一句,grep
(egrep
) 的 -o
选项是一个 GNU 扩展。
Why does this matter "The
-o
option togrep
(egrep
) is a GNU extension"?
并非我使用的机器上所有 grep
的副本都是 GNU grep
— 全世界都不是 Linux 盒子。如果非 Linux 框上的 grep
版本根本不支持 -o
选项或不使用该选项,您将收到一条错误消息或不同的行为与 GNU grep
的含义相同。如果您只处理 Linux 个框,则不必担心;这就是为什么这是一个偶然的评论。
I did not have an issue with
'[^/]+$'
— why do you say it fails?
因为echo /x/y/z/ | grep -o -E '[^/]+$'
没有输出。如果没有尾部斜杠(用于强制名称为目录),则没有问题。这是一个极端主义的案例——你的剧本怎么会被极端的输入破坏。如果 /x/y/z/
是一个目录(或不存在),wc
命令也会失败。