简体   繁体   中英

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. 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:

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:

./callfile "file.txt"

EDIT: replaced ${line} in the read by line , and ${file} with file

I hope we understood your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM