(特定文本是使用 case 语句从文件中的字段派生的)输入文件:
MYFILEA|ssss|1111|
MYFILEB|ffff|2222|
MYFILEC|ssss|3333|
case 语句将使用每行中的第 5 个字符来确定将哪个 case 语句附加到每行
A-'Apple'
B-'Banana'
C-'Carrot'
预期输出:
MYFILEA|ssss|1111|Apple
MYFILEB|ffff|2222|Banana
MYFILEC|ssss|3333|Carrot
我目前的做法是这样的:
rm MYOUTPUT.txt
touch MYOUTPUT.txt
filename="MYINPUT.txt"
while read line
do
ENDTEXT=`echo $line | cut -c7`
#echo $ENDTEXT
case $ENDTEXT in
A)
APPTEXT="Apple" ;;
B)
APPTEXT="Banana" ;;
C)
APPTEXT="Carrots" ;;
*)
APPTEXT="XXXX" ;;
esac
echo $APPTEXT
sed 's/$/'APPTEXT'/' >> MYOUTPUT.txt
答案1
纯bash:
脚本add_column.sh
:
#! /usr/bin/env bash
set -u
# get 1st parameter as input filename
declare -r input_filename="$1"
# key
declare k=
# value
declare v=
# read all lines from input file
while read -r line; do
#echo "l='$line'"
# get key
k="${line:6:1}"
#echo "k='$k'"
# determine value for each key value
case "$k" in
'A')
v='Apple'
;;
'B')
v='Banana'
;;
'C')
v='Carrot'
;;
*)
echo "Unknown key '$k'"
exit 1
;;
esac
# print result
echo "$line$v"
done < "$input_filename"
和:
chmod +x add_column.sh
像这样执行:
add_column.sh input.txt
结果:
MYFILEA|ssss|1111|Apple
MYFILEB|ffff|2222|Banana
MYFILEC|ssss|3333|Carrot