Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何计算通过stdin传递给bash脚本的文件名_Bash - Fatal编程技术网

如何计算通过stdin传递给bash脚本的文件名

如何计算通过stdin传递给bash脚本的文件名,bash,Bash,我想计算通过stdin传递给脚本的文件名,然后在sed命令中使用它。目前,我有以下代码: #!/bin/bash eval file="${1:-/dev/stdin}" echo "$file" sed -i -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' "$file" 称之为: bash callfile < file.txt 为什么此代码无法读取我传递给它的文件名?数据将作为从文件重定向的流传递给您。您的脚本对该文件没有任何

我想计算通过stdin传递给脚本的文件名,然后在sed命令中使用它。目前,我有以下代码:

#!/bin/bash

eval file="${1:-/dev/stdin}"
echo "$file"
sed -i -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' "$file"
称之为:

bash callfile < file.txt

为什么此代码无法读取我传递给它的文件名?

数据将作为从文件重定向的流传递给您。您的脚本对该文件没有任何知识-只有流。再举一个例子,它可能是从另一个进程的输出通过管道传入的数据,因此您没有任何文件可以开始。

正如@Brian Agnew所说,您正在从文档中读取数据,因此很好地使用您的命令行是:

while read -r line; do
    echo ${line} | sed -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba'
done < ${1:-/dev/stdin}
编辑:将
read
中的
${line}
替换为
line
,将
${file}
替换为
file


我希望我们理解了您的问题。

看起来您要求
sed
/dev/stdin
中进行就地替换。它将在哪里写入结果?您将
file
设置为实际字符串
/dev/stdin
Sed无法知道您的意思是从标准输入读取。这正是问题所在。如何将eval
file=“${1:-/dev/stdin}”
设置为“file.txt”而不是“/dev/stdin”,而不在脚本中显式设置它?您是否尝试过
bash callfile file.txt
(没有
@218,您不能同时使用
-I
如果我设置eval=“file.txt”,那么这就行得通了。我想做的是替换它“file.txt”,其文件名由我在stdin中指定,这样我就不必在代码中为我要应用此脚本的每个文件更改此文件。files_list.txt需要采用什么格式。如果我尝试此操作,我只会得到
sed:无法读取:没有这样的文件或目录。
如果我添加一行
echo“${file}“
在这个循环中,我只得到一个空行,因此它显然无法读取我提供的任何文件名。对不起,修复了它。我总是犯这个错误!
while read -r line; do
    echo ${line} | sed -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba'
done < ${1:-/dev/stdin}
./callfile < files_list.txt

while read -r file; do
    sed -i -r ':a; s%(.*)/\*.*\*/%\1%; ta; /\/\*/ !b; N; ba' "${file}"
done < ${1:-/dev/stdin}
./callfile "file.txt"