开发者

Read line by line from different locations please help to avoid duplicated code

开发者 https://www.devze.com 2023-02-26 02:01 出处:网络
I\'ve the following script. for args do while read line; do # do something done <\"$args\" done If 开发者_如何学编程the script is started with a list of filenames, it should read out each fi

I've the following script.

for args 
do 
        while read line; do
                # do something
        done <"$args"

done 

If 开发者_如何学编程the script is started with a list of filenames, it should read out each file line by line.

Now I'm looking for a way the read from stdin when script is started without a list of filenames, but I doesn't want to duplicate the while loop.

Any ideas?


Quick answer:

[[ -z $1 ]] && defaultout=/dev/stdin

for f in "$@" $defaultout; do
  while read line; do
    # do something
  done < "$f"
done

Drawback: parameters are not parsed

Second attempt:

[[ -z $1 ]] && defaultout=/dev/stdin

for f in $@ $defaultout; do
  if [[ -f $f ]]; then
    while read line; do
      # do something
    done < "$f"
  fi
done

Drawback: Filenames with spaces will be parsed into two words.


You could try:

args="$*"
if [ "$args" = "" ]; then
  args=/dev/stdin;
fi

for arg in $args; do
  while read -r line; do
    # do something
  done < "$arg";
done


The following should do what you want:

cat "$@" | while read line; do
  # something
done
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号