gpt4 book ai didi

linux - Bash 脚本 - 从标准输入或文件获取输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:39 26 4
gpt4 key购买 nike

我有一个 bash 脚本,它按从命令行获取的名称打印列。如果我将文件作为参数之一提供给脚本,效果会很好。如果我将输入通过管道传递给脚本并使用/dev/stdin 作为文件,则效果不佳。有谁知道我如何修改脚本以正确接受来自管道的标准输入?这是我的脚本。

#!/bin/bash

insep=" "
outsep=" "
while [[ ${#} > 0 ]]
do
option="$1"
if [ -f $option ] || [ $option = /dev/stdin ];
then
break;
fi
case $option in
-s|--in_separator)
insep="$2"
shift # past argument
shift # past argument
;;
-o|--out_separator)
outsep="$2"
shift # past argument
shift # past argument
;;
*)
echo "unknown option $option"
exit 1;
;;
esac
done

headers="${@:2}"
grep_headers=$(echo "${headers[@]}" | sed 's/ /|/g')
file=$1

columns=$(awk -F: 'NR==FNR{b[($2)]=tolower($1);next}{print $1,b[$1]}' \
<(head -1 $file | sed "s/$insep/\n/g" | egrep -iwn "$grep_headers" | awk '{s=tolower($0);print s}') \
<(awk -F: -v header="$headers" 'BEGIN {n=split(tolower(header),a," ");for(i=1;i<=n;i++) print a[i]}' $file ) \
| awk '{print "$"$2}' ORS='OFS' | sed "s/OFS\$//")

awk -v insep="$insep" -v outsep="$outsep" "BEGIN{FS=insep;OFS=outsep}{print $columns}" $file

exit;

示例输入:

col_1 col_2 col_3 col_4 col_5 col_6 col_7 col_8 col_9 col_10
10000 10010 10020 10030 10040 10050 10060 10070 10080 10090
10001 10011 10021 10031 10041 10051 10061 10071 10081 10091
10002 10012 10022 10032 10042 10052 10062 10072 10082 10092
10003 10013 10023 10033 10043 10053 10063 10073 10083 10093
10004 10014 10024 10034 10044 10054 10064 10074 10084 10094
10005 10015 10025 10035 10045 10055 10065 10075 10085 10095
10006 10016 10026 10036 10046 10056 10066 10076 10086 10096
10007 10017 10027 10037 10047 10057 10067 10077 10087 10097
10008 10018 10028 10038 10048 10058 10068 10078 10088 10098

以文件作为参数运行(按预期工作):

> ./shell_scripts/print_columns.sh file1.txt col_1 col_4 col_6 col_2 | head
col_1 col_4 col_6 col_2
10000 10030 10050 10010
10001 10031 10051 10011
10002 10032 10052 10012
10003 10033 10053 10013

来自标准的管道(未按预期工作):

> head file1.txt | ./shell_scripts/print_columns.sh /dev/stdin col_1 col_4 col_6 col_2 | head
0185 10215 10195
10136 10166 10186 10146
10137 10167 10187 10147
10138 10168 10188 10148
10139 10169 10189 10149

最佳答案

一个例子:

脚本.sh:

#!/bin/bash

if [[ -f "$1" ]]; then
file="$1"
cat "$file"
shift
else
while read -r file; do echo "$file"; done
fi
echo "${@}"

测试:

./script.sh file1.txt abc 123 456

UUOC :

cat file1.txt | ./script.sh abc 123 456

关于linux - Bash 脚本 - 从标准输入或文件获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com