[英]How can I evaluate the filename passed to a bash script via stdin
I would like to evaluate a filename passed to a script via stdin and then use this in a sed command. 我想评估通过stdin传递给脚本的文件名,然后在sed命令中使用它。 At the moment I have the following code:
目前,我有以下代码:
#!/bin/bash
eval file="${1:-/dev/stdin}"
echo "$file"
sed -i -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' "$file"
Calling this as: 将此称为:
bash callfile < file.txt
results in the following error: 导致以下错误:
/dev/stdin
sed: couldn't open temporary file /dev/sedSVVTdr: Permission denied
Why is this code unable to read the filename I pass to it? 为什么此代码无法读取我传递给它的文件名?
That data is getting passed to you as a stream redirected from the file. 这些数据将作为从文件重定向的流传递给您。 Your script won't have any knowledge of that file - only the stream.
您的脚本将对该文件一无所知-仅对流有所了解。 As a further example, it could be data piped in from the output of another process, and so you wouldn't have any file to begin with.
再举一个例子,它可以从另一个进程的输出中通过数据管道输入,因此您无需任何文件。
As @Brian Agnew said, you are reading from your document, so a good use of your command line is: 正如@Brian Agnew所说,您正在阅读文档,因此可以很好地使用命令行:
while read -r line; do
echo ${line} | sed -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba'
done < ${1:-/dev/stdin}
Note that is you have a list of files in a file, you can then run your process as intended: 请注意,如果文件中有文件列表,则可以按预期运行进程:
./callfile < files_list.txt
while read -r file; do
sed -i -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' "${file}"
done < ${1:-/dev/stdin}
but at the moment, there is no advantage of reading from stdin
, so: 但是目前,从
stdin
读取没有任何优势,因此:
./callfile "file.txt"
EDIT: replaced ${line}
in the read
by line
, and ${file}
with file
编辑:替换
${line}
在read
的line
,和${file}
与file
I hope we understood your question. 希望我们能理解您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.